自定义404响应模型

时间:2016-07-09 06:06:55

标签: asp.net-core asp.net-core-mvc asp.net-core-1.0

我想在API上为所有404提供自定义响应。例如:

{
  "message": "The requested resource does not exist. Please visit our documentation.."
}

我相信以下结果过滤器适用于MVC管道中的所有情况:

public class NotFoundResultFilter : ResultFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        var result = context.Result as NotFoundResult;

        if (result != null)
        {
            context.Result = new HttpNotFoundResult(); // My custom 404 result object
        }
    }
}

但是,当请求的URL与操作路由不匹配时,不会触发上面的过滤器。 我怎样才能最好地拦截这些404响应?这需要中间件吗?

1 个答案:

答案 0 :(得分:5)

是的,您需要使用中间件,因为过滤器仅适用于MVC。

  1. 您可以像往常一样编写自己的中间件

    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Response.ContentType = "application/json";
    
            await context.Response.WriteAsync(JsonConvert.SerializeObject("your text"), Encoding.UTF8);
        }
    });
    
  2. 或者使用内置的middlware StatusCodePagesMiddleware,但由于您只想处理一种状态,因此这是一项额外的功能。此中间件可用于处理400到600之间的响应状态代码。您可以配置StatusCodePagesMiddleware,将以下行之一添加到Configure方法(例如来自StatusCodePages Sample):

    app.UseStatusCodePages(); // There is a default response but any of the following can be used to change the behavior.
    
    // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
    // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
    // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
    // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
    // app.UseStatusCodePages(builder => builder.UseWelcomePage());
    // app.UseStatusCodePagesWithReExecute("/errors/{0}");