ASP MVC控制器重定向到错误页面

6
我有一个简单的问题。如何从控制器重定向到自定义错误页面并返回HTTP状态码? 例如:
public ActionResult Index()
{
   this.Redirect("Not found", 404); //redirect to my error page with code 404
}

只需返回视图, return View("视图名称"); - Balu
返回new HttpNotFoundResult(),然后使用内置的错误处理。 - Chris Pratt
1个回答

11

将以下代码添加到 web.config 文件中:

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

在控制器中添加以下代码:

public class ErrorController : Controller{
public ViewResult Index()
{
    return View("Error");
}
public ViewResult NotFound()
{
    Response.StatusCode = 404;  //you may want to set this to 200
    return View("NotFound");
}}

没起作用。我做的一切都和上面完全一样,只是用了“Error404”代替“NotFound”。控制器到达那里,但我得到了:Error/Error404?aspxerrorpath=/Dashboaord。当我将Error404.cshtml移出Error文件夹时,它会重定向到通用错误页面。 - Clarence

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接