1

I have tried many method, but still fail to make it. Just want to show a 404/500 when the request is invalid.

Eg. There have no User Id = 100, if someone make this request, it should return 404. On the other hand, Throw 500, if server error happened.

I want this behavior to apply entire apps.

public ActionResult EditUser(int Id)
    {
        var db = new UserDbContext();
        var usr = db.Users.Where(a => a.Id == Id).SingleOrDefault();
        if (usr == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound, "User not found");
        return View(usr);
    }

with webconfig in system.web

<customErrors mode="On"  redirectMode="ResponseRewrite" defaultRedirect="~/General">
  <error statusCode="404" redirect="~/NotFound" />
  <error statusCode="403" redirect="~/BadRequest" />
</customErrors>

and in system.webserver

<httpErrors existingResponse="PassThrough"></httpErrors>

Tried many combination way, cannot make it work. The result i get is a empty page, then browser console showing the 404/500 error. But I want it to show on page.

Someone could please point out my mistake. Thanks

Eric K.
  • 814
  • 2
  • 13
  • 22
  • Check if it's because of the web.config http://stackoverflow.com/questions/4483849/default-redirect-for-error-404 – Offir Aug 11 '16 at 08:37

3 Answers3

2

you can use

throw new HttpException(404, "HTTP/1.1 404 Not Found");

or

return HttpNotFound();

or return error view form shared folder

return View("NotFound");
shady youssery
  • 430
  • 2
  • 17
0

you can add

public ActionResult EditUser(int Id)
    {
        var db = new UserDbContext();
        var usr = db.Users.Where(a => a.Id == Id).SingleOrDefault();
        if (usr == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound, "User not found");
        Response.StatusCode = 400;
        return View(usr);
    }
Emil
  • 281
  • 1
  • 2
  • 11
0

Just throw/return HTTP Exceptions like this:

throw new HttpException(404, "Some description");.

Or return new HttpNotFoundResult("optional description"); for ASP.NET MVC 3 and above.

Or return HttpNotFound("I did not find message goes here"); for MVC 4 and above.

Raskayu
  • 735
  • 7
  • 20
  • I like the code you show, but the result is same, the white blank window, and console printe 404 not found. I was thinking, must be something wrong on my config. But I dont know where. – Eric K. Aug 12 '16 at 02:40
  • @EricK.Watch the second answer http://stackoverflow.com/questions/553922/custom-asp-net-mvc-404-error-page – Raskayu Aug 12 '16 at 06:12