我在.NET Core 2.1 Web应用程序中使用UseStatusCodePagesWithReExecute,如下所示
app.UseStatusCodePagesWithReExecute("/Error/{0}");
在控制器中,我指向2个视图中的1个,即404.cshtml视图和一般error.cshtml视图
public class ErrorController : Controller
{
[HttpGet("[controller]/{statusCode:int}")]
public IActionResult Error(int? statusCode = null)
{
if (statusCode.HasValue)
{
if (statusCode == (int)HttpStatusCode.NotFound)
{
return View(statusCode.ToString());
}
}
return View();
}
}
现在,在页面控制器中,我可以执行以下操作,并且按预期方式工作。它将显示error.cshtml
public IActionResult SomePage()
{
return BadRequest();
}
现在,如果我将以上内容更改为以下内容,我的ErrorController确实会被命中,但是到了它出现空白视图时,浏览器中仅显示了“某些详细信息”。
public IActionResult SomePage()
{
return BadRequest("Some details");
}
任何想法为何?我希望它加载error.cshtml
答案 0 :(得分:0)
正如@Kirk Larkin所说,UseStatusCodePagesWithReExecute中间件将无法工作,并且只能处理状态代码。
您可以使用Result过滤器来编写自定义逻辑以对其进行过滤并返回ViewResult:
public class StatusCodeResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// retrieve a typed controller, so we can reuse its data
if (context.Controller is Controller controller)
{
// intercept the NotFoundObjectResult
if (context.Result is BadRequestObjectResult badRequestObject)
{
// set the model, or other view data
controller.ViewData.Model = badRequestObject.Value;
// replace the result by a view result
context.Result = new ViewResult()
{
StatusCode = 400,
ViewName = "Views/Error/status400.cshtml",
ViewData = controller.ViewData,
TempData = controller.TempData,
};
}
}
await next();
}
}
注册过滤器:
services.AddMvc(config =>
{
config.Filters.Add(new StatusCodeResultFilter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
您认为,您可以通过以下方式直接获取详细信息:
@Model