How to get MVC action to return 404

后端 未结 12 1752
日久生厌
日久生厌 2020-12-23 02:53

I have an action that takes in a string that is used to retrieve some data. If this string results in no data being returned (maybe because it has been deleted), I want to r

相关标签:
12条回答
  • 2020-12-23 03:09

    In MVC 4 and above you can use the built-in HttpNotFound helper methods:

    if (notWhatIExpected)
    {
        return HttpNotFound();
    }
    

    or

    if (notWhatIExpected)
    {
        return HttpNotFound("I did not find message goes here");
    }
    
    0 讨论(0)
  • 2020-12-23 03:13

    I've used this:

    Response.StatusCode = 404;
    return null;
    
    0 讨论(0)
  • 2020-12-23 03:16

    There are multiple ways to do it,

    1. You are right in common aspx code it can be assigned in your specified way
    2. throw new HttpException(404, "Some description");
    0 讨论(0)
  • 2020-12-23 03:20

    If you are working with .NET Core, you can return NotFound()

    0 讨论(0)
  • 2020-12-23 03:25

    Code :

    if (id == null)
    {
      throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
    }
    

    Web.config

    <customErrors mode="On">
      <error statusCode="404" redirect="/Home/NotFound" />
    </customErrors>
    
    0 讨论(0)
  • 2020-12-23 03:26

    Please try the following demo code:

    public ActionResult Test()
    
    {
      return new HttpStatusCodeResult (404,"Not found");
    }
    
    0 讨论(0)
提交回复
热议问题