http status code 404 - Returning 404 Error ASP.NET MVC 3 -
i have tried following 2 things have page return 404 error:
public actionresult index() { return new httpstatuscoderesult(404); } public actionresult notfound() { return httpnotfound(); } but both of them render blank page. how can manually return 404 error within asp.net mvc 3?
if inspect response using fiddler, believe you'll find blank page in fact returning 404 status code. problem no view being rendered , blank page.
you actual view displayed instead adding customerrors element web.config redirect user specific url when status code occurs can handle url. here's walk-through below:
first throw httpexception applicable. when instantiating exception, sure use 1 of overloads takes http status code parameter below.
throw new httpexception(404, "notfound"); then add custom error handler in web.config file determine view should rendered when above exception occurs. here's example below:
<configuration> <system.web> <customerrors mode="on"> <error statuscode="404" redirect="~/404"/> </customerrors> </system.web> </configuration> now add route entry in global.asax that'll handle url "404" pass request controller's action that'll display view 404 page.
global.asax
routes.maproute( "404", "404", new { controller = "commons", action = "httpstatus404" } ); commonscontroller
public actionresult httpstatus404() { return view(); } all that's left add view above action.
one caveat above method: according book "pro asp.net 4 in c# 2010" (apress) use of customerrors outdated if you're using iis 7. instead should use httperrors section. here's quote book:
but although setting still works visual studio’s built-in test web server, it’s been replaced
<httperrors>section in iis 7.x.
Comments
Post a Comment