Redirect to 404 page programmatically using asp.net MVC

ⅰ亾dé卋堺 提交于 2019-12-20 18:34:17

问题


I have created a Asp.net MVC application. Now required 404 handling.

Have updated global.asax and display 404 page based on status code. Also added customErrors property in web.config. Its working fine.

Now I would like to redirect to 404 programmatically when any thing not match with our requirement.

i.e.

if(!valid) 
{
    return RedirectToAction("Index", "Page404");
}

It's working fine but there are 2 status one is 301 & then 404. So how can I prevent 301? I just need 404.

How can I achieve this?


回答1:


In your web.config, add:

<customErrors mode="On" >
       <error statusCode="404" redirect="/404.shtml" />
</customErrors>

This will redirect on 404.shtml page when requested resource is not found.

Note: No need to programmatically redirect users for such situation.


EDIT: I literally suggest:

if (Context.Response.StatusCode == 404) {
  // handle this
}



回答2:


Simply return from your action:

return HttpNotFound();



回答3:


Just throw out a 404 in the status code:

Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound


来源:https://stackoverflow.com/questions/10702631/redirect-to-404-page-programmatically-using-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!