How to get MVC action to return 404

后端 未结 12 1754
日久生厌
日久生厌 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 02:59

    None of the above examples worked for me until I added the middle line below:

    public ActionResult FourOhFour()
    {
        Response.StatusCode = 404;
        Response.TrySkipIisCustomErrors = true; // this line made it work
        return View();
    }
    
    0 讨论(0)
  • 2020-12-23 03:04

    In NerdDinner eg. Try it

    public ActionResult Details(int? id) {
        if (id == null) {
            return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
        }
        ...
    }
    
    0 讨论(0)
  • 2020-12-23 03:04

    In .NET Core 1.1:

    return new NotFoundObjectResult(null);
    
    0 讨论(0)
  • 2020-12-23 03:06

    You can also do:

            if (response.Data.IsPresent == false)
            {
                return StatusCode(HttpStatusCode.NoContent);
            }
    
    0 讨论(0)
  • 2020-12-23 03:07

    In ASP.NET MVC 3 and above you can return a HttpNotFoundResult from the controller.

    return new HttpNotFoundResult("optional description");
    
    0 讨论(0)
  • 2020-12-23 03:07

    I use:

    Response.Status = "404 NotFound";
    

    This works for me :-)

    0 讨论(0)
提交回复
热议问题