简体   繁体   English

当找不到资源(url)时,Web API 2.2返回自定义404

[英]Web API 2.2 return custom 404 when resource (url) not found

I want to be able to take over the 404 response from web api (iis) when the resource does not exist. 我希望能够在资源不存在时从web api(iis)接管404响应。

I have done my research and came across only one solution that made this work, but i am not sure how "safe" it is since the "routeTemplate" is just {*url} 我已经完成了我的研究,并且只遇到了一个使这项工作成功的解决方案 ,但我不确定它是多么“安全”,因为“routeTemplate”只是{* url}

This post is kinda to ask for help and explanation. 这篇文章有点请求帮助和解释。

My App uses MVC and WebAPI... would this template affect MVC as well? 我的应用程序使用MVC和WebAPI ...这个模板也会影响MVC吗? Is there a way to add "api" with {*url} in the template? 有没有办法在模板中添加带有{* url}的“api”? (to make sure only requests with ".../api/..." get affected) (以确保只有“... / api / ...”的请求受到影响)

config.Routes.MapHttpRoute("Error404", "{*url}", new { controller = "Error", action = "Handle404" });

Has anyone come across a cleaner way of doing this and handling 404 in web api? 有没有人遇到过这样做更清洁的方式并在web api中处理404?

EDIT 1 编辑1

The above code DOES affect my MVC routes. 上面的代码会影响我的MVC路由。 How can i add "api" to "{*url}"?... if tried many different ways and no dice. 如何将“api”添加到“{* url}”?...如果尝试了许多不同的方式而没有骰子。

Had the exact same issue. 有完全相同的问题。 After some research and trial and error, I was able to find a working solution. 经过一些研究和反复试验,我找到了一个有效的解决方案。

I went with a RoutePrefix solution and I tried to implement something similar to how the MVC controllers used HandleUnknownAction in a base controller. 我使用了RoutePrefix解决方案,并尝试实现类似于MVC控制器如何在基本控制器中使用HandleUnknownAction的方法。

With the help from this post: .NET WebAPI Attribute Routing and inheritance to allow for route inheritance, I created a base controller for my web APIs with a HandleUnknownAction method like this: 在这篇文章的帮助下: .NET WebAPI属性路由和继承以允许路由继承,我使用HandleUnknownAction方法为我的Web API创建了一个基本控制器,如下所示:

public abstract class WebApiControllerBase : ApiController {

    [Route("{*actionName}")]
    [AcceptVerbs("GET", "POST", "PUT", "DELETE")]//Include what ever methods you want to handle
    [AllowAnonymous]//So I can use it on authenticated controllers
    [ApiExplorerSettings(IgnoreApi = true)]//To hide this method from helpers
    public virtual HttpResponseMessage HandleUnknownAction(string actionName) {
        var status = HttpStatusCode.NotFound;
        //This is custom code to create my response content
        //....
        var message = status.ToString().FormatCamelCase();
        var content = DependencyService
            .Get<IResponseEnvelopeFactory>()
            .CreateWithOnlyMetadata(status, message);
        //....
        return Request.CreateResponse(status, content);
    }
}

If you don't want to go down the inheritance path, you can always put the method directly into the controller you want to apply the functionality on. 如果您不想沿着继承路径前进,则可以始终将方法直接放入要应用该功能的控制器中。

This allows me to use route prefixes that handle custom not found messages that pertain to specific controllers as I have both back-office and public public facing APIs. 这允许我使用处理与特定控制器有关的自定义未找到消息的路由前缀,因为我有后台和面向公众的API。

If a URL does not apply to an ApiController the default Error controller will handle the not found as usual. 如果URL不适用于ApiController则默认的错误控制器将像往常一样处理未找到的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM