Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自定义“未找到与请求uri匹配的http资源”消息_C#_Asp.net_.net_Asp.net Web Api - Fatal编程技术网

C# 自定义“未找到与请求uri匹配的http资源”消息

C# 自定义“未找到与请求uri匹配的http资源”消息,c#,asp.net,.net,asp.net-web-api,C#,Asp.net,.net,Asp.net Web Api,有没有一种简单的方法来修改WebAPI返回的默认404消息 未找到与请求uri匹配的http资源 您需要重写抽象类 在这里看到更多 在这里,实现这一点的简单方法是授权处理者 第一步是创建从DelegatingHandler继承的新类: public class ApiGatewayHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAs

有没有一种简单的方法来修改WebAPI返回的默认404消息

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

您需要重写抽象类

在这里看到更多


在这里,

实现这一点的简单方法是授权处理者

第一步是创建从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中的更新所建议的那样使用OWIN中间件?当然,您可以使用OWIN中间件。我的建议是两种方法都试一下,看看哪一种更适合你
public static void Register(HttpConfiguration config){
    public static void Register(HttpConfiguration config)
    {
        // you config and routes here                

        config.MessageHandlers.Add(new ApiGatewayHandler());

        //....
    }
}