将所有Web API请求路由到一个控制器方法

编程入门 行业动态 更新时间:2024-10-26 01:29:13
本文介绍了将所有Web API请求路由到一个控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以自定义ASP.NET Web API的路由机制,以将对API的所有请求路由到一个控制器方法?

Is it possible to customize ASP.NET Web API's routing mechanism to route all requests to the API to one controller method?

如果有请求

www.mysite/api/products/

www.mysite/api/otherResource/7

所有内容都将路由到我的SuperDuperController的Get()方法吗?

All would be routed to my SuperDuperController's Get() method?

推荐答案

我遇到了需要这样做的情况. (Web API 2)

I ran into a case where I needed to do this. (Web API 2)

我首先研究了如何创建自定义的IHttpControllerSelector和IHttpActionSelector s.但是,这有点模糊.因此,我最终决定采用这种简单的实现方式.您所要做的就是设置通配符路由.示例:

I first looked into creating custom IHttpControllerSelector and IHttpActionSelectors. However, that was a bit of a murky way around. So I finally settled on this dead simple implementation. All you have to do is setup a wildcard route. Example:

public class SuperDuperController : ApiController { [Route("api/{*url}")] public HttpResponseMessage Get() { // url information Request.RequestUri // route values, including "url" Request.GetRouteData().Values } }

任何以"api/"开头的GET请求都将被路由到上述方法.这包括您问题中的上述URL.您必须自己从Request或上下文对象中挖掘信息,因为这会绕过自动路由值和模型解析.

Any GET request that starts with "api/" will get routed to the above method. That includes the above mentioned URLs in your question. You will have to dig out information from the Request or context objects yourself since this circumvents automatic route value and model parsing.

这样做的好处是,您仍然可以使用其他控制器(只要它们的路由不是以"api/"开头).

The good thing about this is you can still use other controllers as well (as long as their routes don't start with "api/").

更多推荐

将所有Web API请求路由到一个控制器方法

本文发布于:2023-11-16 21:01:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607440.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   控制器   方法   Web   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!