Eric K.
Eric K.

Reputation: 834

MVC Simple Error Handle BadRequest

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

Upvotes: 1

Views: 3394

Answers (3)

shady youssery
shady youssery

Reputation: 440

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");

Upvotes: 2

Raskayu
Raskayu

Reputation: 743

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.

Upvotes: 0

Emil
Emil

Reputation: 281

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);
    }

Upvotes: 0

Related Questions