MVC 4 HttpNotFound()和404错误

时间:2022-11-29 13:53:45

I have a controller in which I am processing a part of the url and if it matches some criteria I will return a View but if not I will return a HttpNotFound().

我有一个控制器,我在其中处理网址的一部分,如果它符合某些条件,我将返回一个视图,但如果不是,我将返回一个HttpNotFound()。

Now I have set up a friendly 404 page which a user will be redirected to if a 404 is thrown so why doesn't the HttpNotFound redirect to this page?

现在我已经建立了一个友好的404页面,如果抛出404,用户将被重定向到该页面,为什么HttpNotFound不会重定向到此页面?

I would expect the 404 to be thrown then the page to be redirected to the error page as set up in the web.config but it just shows the default 404 page. I have checked with other urls that don't exist and these all redirect to the proper error page

我希望404被抛出,然后将页面重定向到web.config中设置的错误页面,但它只显示默认的404页面。我已经检查了其他不存在的URL,这些都重定向到正确的错误页面

2 个解决方案

#1


5  

As it turns out you're meant to throw an exception:

事实证明你是要抛出异常:

throw new HttpException(404, "Page Not Found");

This seems to handle the 404 and then redirect you to the proper page rather than just the IIS 404 page

这似乎处理404,然后将您重定向到正确的页面而不仅仅是IIS 404页面

#2


2  

Just taking a guess...

只是猜一猜......

The reason that you are not redirected to the friendly 404 page is because IIS/MVC were able to process the request. Then when processing the request you determine that you needed to return a 404 status code to the client.

您没有被重定向到友好的404页面的原因是因为IIS / MVC能够处理请求。然后,在处理请求时,您确定需要将404状态代码返回给客户端。

Personally, I prefer to return a 404 status code and my PageNotFound view similar to this approach that is used by *: https://*.com/a/499907/84395

就个人而言,我更喜欢返回404状态代码和我的PageNotFound视图,类似于*使用的这种方法:https://*.com/a/499907/84395

#1


5  

As it turns out you're meant to throw an exception:

事实证明你是要抛出异常:

throw new HttpException(404, "Page Not Found");

This seems to handle the 404 and then redirect you to the proper page rather than just the IIS 404 page

这似乎处理404,然后将您重定向到正确的页面而不仅仅是IIS 404页面

#2


2  

Just taking a guess...

只是猜一猜......

The reason that you are not redirected to the friendly 404 page is because IIS/MVC were able to process the request. Then when processing the request you determine that you needed to return a 404 status code to the client.

您没有被重定向到友好的404页面的原因是因为IIS / MVC能够处理请求。然后,在处理请求时,您确定需要将404状态代码返回给客户端。

Personally, I prefer to return a 404 status code and my PageNotFound view similar to this approach that is used by *: https://*.com/a/499907/84395

就个人而言,我更喜欢返回404状态代码和我的PageNotFound视图,类似于*使用的这种方法:https://*.com/a/499907/84395