自定义404响应模型 [英] Custom 404 response model

查看:160
本文介绍了自定义404响应模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我们API上的所有404提供自定义响应.例如:

I want to provide a custom reponse for all 404s on our API. For example:

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

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

I believe the following result filter works for all cases within the MVC pipeline:

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个响应?这需要中间件吗?

But, when a URL requested does not match an action route, the above filter is not hit. How could I best intercept these 404 responses? Would this require middleware?

推荐答案

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

Yes, you need to use middleware, as filter is only for MVC.

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

  1. You may, as always, write your own middleware

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);
    }
});

  • 或使用内置的中间件 StatusCodePagesMiddleware ,但是由于您只想处理一种状态,因此这是一项额外的功能.此中间件可用于处理400到600之间的响应状态代码.您可以配置StatusCodePagesMiddleware,将以下行之一添加到Configure方法中(示例来自

  • Or use built-in middlware StatusCodePagesMiddleware, but as you want to handle only one status, this is an extra functionality. This middleware can be used to handle the response status code is between 400 and 600 .You can configure the StatusCodePagesMiddleware adding one of the following line to the Configure method (example from 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}");
    

  • 这篇关于自定义404响应模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆