简体   繁体   English

ASP.NET Web API 更改请求 URI(重定向到另一种方法)

[英]ASP.NET Web API change request URI (Redirect to another method)

I have an ASP.NET project in which API versioning has been implemented via URL versioning.我有一个 ASP.NET 项目,其中 API 版本控制是通过 URL 版本控制实现的。 eg:例如:

api/v1/Resource
api/v2/Resource

Now the requirement is that if a user requests a resource which is not available in that version, then it should fallback to previous version.现在的要求是,如果用户请求的资源在该版本中不可用,则它应该回退到以前的版本。 Let's say user wants to access api/v2/SomeResource but the same is not available, then request should be forwarded to api/v1/SomeResource .假设用户想要访问api/v2/SomeResource但同样不可用,则应将请求转发到api/v1/SomeResource

Can we intercept every incoming request and change the RequestURI before Route is decided?我们可以在决定路由之前拦截每个传入的请求并更改 RequestURI 吗?

I have tried using a DelegatingHandler to change the Request URI, but seems like route is decided before DelegatingHandler is executed.我曾尝试使用DelegatingHandler来更改请求 URI,但似乎路由是在执行 DelegatingHandler 之前决定的。

protected override Task<HttpResponseMessage> SendAsync
    (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    request.RequestUri = new Uri(getNewURI(request.RequestUri.AbsoluteUri), UriKind.Absolute);
    return base.SendAsync(request, cancellationToken);
}

Is there anyway we can change the ReqestURI before Routing is finalized by Web API or any other way to accomplish this kind of redirection?无论如何,我们可以在 Web API 最终确定路由之前更改 ReqestURI 或以任何其他方式完成这种重定向吗?

If you already know ahead of time that the route no longer exists (you would have to if you knew which route you wanted to redirect to) then you could just add multiple routes to the same method.如果您已经提前知道该路由不再存在(如果您知道要重定向到哪条路由,则必须知道),那么您可以向同一个方法添加多个路由。 Otherwise you would have to call the route to see if it existed, if it gave a 404 you would then have to attempt again with the next one and so on.否则,您将不得不调用该路由以查看它是否存在,如果它给出了 404,则您将不得不再次尝试使用下一个,依此类推。

[HttpGet, Route("api/v2/resource")]
[HttpGet, Route("api/v1/resource")]
public IHttpActionResult YourMethod()
{

}

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

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