问题描述
我曾尝试以下两件事情有一个页面返回404错误:
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();
}
但他们两人只是呈现一个空白页。如何我手动从ASP.NET MVC 3?
but both of them just render a blank page. How can I manually return a 404 error from within ASP.NET MVC 3?
推荐答案
如果您使用招检查响应,我相信你会发现空白页,其实是返回404状态code。问题是没有被渲染视图,从而空白页。
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.
您可以获取要通过添加的customErrors元素,你的web.config,而不是显示实际的观点,即当将一定地位code发生然后你就可以处理,你会与将用户重定向到一个特定的网址任何URL。这里有一个步行通过如下:
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:
首先抛出适用。当实例化异常,一定要使用这需要一个HTTP状态code像下面的参数重载之一。
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");
然后在你的web.config文件中添加自定义错误处理程序,以便你能确定何时上述异常发生什么看法应该呈现。下面是下面一个例子:
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>
现在添加在Global.asax中的路由条目会处理的URL404,这将请求传递给控制器的作用是将显示你的404页查看。
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中
Global.asax
routes.MapRoute(
"404",
"404",
new { controller = "Commons", action = "HttpStatus404" }
);
CommonsController
CommonsController
public ActionResult HttpStatus404()
{
return View();
}
所有剩下的就是增加一个视图上述操作。
All that's left is to add a view for the above action.
一个需要注意上面的方法:据C#2010 Pro的ASP.NET 4(A preSS)使用的是如果你使用IIS 7相反,你应该使用的部分。下面是从书中报价:
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:
不过,尽管这个设置还是使用Visual Studio的内置测试网络工程
服务器,它有效地取代了&LT; httpErrors方式&gt;
在IIS 7.x的部分。
这篇关于返回404错误ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!