没有找到与请求匹配的http资源.消息

本文关键字:http 资源 消息 请求 | 更新日期: 2023-09-27 18:03:50

是否有一种简单的方法来修改Web API返回的默认404消息?

没有找到与请求uri匹配的http资源

没有找到与请求匹配的http资源.消息

你需要重写DelegatingHandler抽象类。

来自ASP的统一、一致的错误响应。Net Web API 2

和这里的ASP。. NET Web API异常处理

简单的方法是通过"DelegatingHandler"

  1. 第一步是创建一个继承自DelegatingHandler的新类:

        public class ApiGatewayHandler : DelegatingHandler
        { 
           protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
           {
             var response = await base.SendAsync(request, cancellationToken);
            if (response!=null && response.StatusCode == HttpStatusCode.NotFound)
            {
                var msg = await response.Content.ReadAsStringAsync();
                //you can change the response here
                if (msg != null && msg.Contains("No HTTP resource was found"))
                {
                    return new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.NotFound,
                        Content = new ObjectContent(typeof(object), new { Message = "New Message..No HTTP resource was found that matches the request URI" }, new JsonMediaTypeFormatter())
                    };
                }
            }
            return response;
        return response;
    }
    

    }

  2. 然后将这个类注册到web api注册配置文件

    public static void Register(HttpConfiguration config){
        public static void Register(HttpConfiguration config)
        {
            // you config and routes here                
            config.MessageHandlers.Add(new ApiGatewayHandler());
            //....
        }
    }
    

就是这样。同样的方法,如果你需要改变任何其他错误信息