Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

http status code 404 - Returning 404 Error ASP.NET MVC 3

I have tried the following 2 things to have a page return a 404 error:

public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}

but both of them just render a blank page. How can I manually return a 404 error from within ASP.NET MVC 3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you inspect the response using fiddler, I believe you'll find that the blank page is in fact returning a 404 status code. The problem is no view is being rendered and thus the blank page.

You could get an actual view to be displayed instead by adding a customErrors element to your web.config that will redirect the user to a specific url when a certain status code occurs which you can then handle as you would with any url. Here's a walk-through below:

First throw the HttpException where applicable. When instantiating the exception, be sure to use one of the overloads which takes a http status code as a parameter like below.

throw new HttpException(404, "NotFound");

Then add an custom error handler in your web.config file so that you could determine what view should be rendered when the above exception occurs. Here's an example below:

<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="404" redirect="~/404"/>
        </customErrors>
    </system.web>
</configuration>

Now add a route entry in your Global.asax that'll handle the url "404" which will pass the request to a controller's action that'll display the View for your 404 page.

Global.asax

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" }
);

CommonsController

public ActionResult HttpStatus404()
{
    return View();
}

All that's left is to add a view for the above action.

One caveat with the above method: according to the book "Pro ASP.NET 4 in C# 2010" (Apress) the use of customErrors is outdated if you're using IIS 7. Instead you should use the httpErrors section. Here's a quote from the book:

But although this setting still works with Visual Studio’s built-in test web server, it’s effectively been replaced by the <httpErrors> section in IIS 7.x.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...