简体   繁体   English

使用ASP.NET限制API路由到控制器名称空间

[英]Restrict API route to controller namespace with ASP.NET

I have found a similar question that relates to standard asp.net controllers, but i have tried it and it doesn't seem to be working with the apicontroller. 我发现了一个与标准asp.net控制器有关的类似问题,但是我已经尝试过了,它似乎无法与apicontroller一起使用。

Restrict route to controller namespace in ASP.NET Core 限制到ASP.NET Core中的控制器名称空间的路由

I want to allow for an API to be deprecated in the future without needing to change the url. 我想允许将来不推荐使用API​​,而无需更改URL。 To solve this i will put a version prefix at the start of the route. 为了解决这个问题,我将在路由的开头放置一个版本前缀。 This way i can add some modifications to an endpoint without breaking any integrations with this API. 这样,我可以对端点添加一些修改,而不会破坏与此API的任何集成。

    config.Routes.MapHttpRoute(
        name: "V1 API",
        routeTemplate: "v1/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }

    );
    config.Routes.MapHttpRoute(
        name: "V2 API",
        routeTemplate: "v2/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }

    );

I want to keep the same controller names and in most cases everything will be the exact same, the response and request body will be the only things that change. 我想保持相同的控制器名称,并且在大多数情况下,所有内容都将完全相同,唯一的变化就是响应和请求正文。 I have tried to add a subdirectory in the controllers folder in order to add v1 and v2 to the namespace of the controller, but i get an error about there being 2 controllers having the same name. 我试图在controllers文件夹中添加一个子目录,以便将v1和v2添加到控制器的名称空间,但是我收到有关2个具有相同名称的控制器的错误。

How can i modify the routes so that it will point to the v1 namespace for the controller instead of just searching for any class within the controller. 我如何修改路由,使其指向控制器的v1名称空间,而不仅仅是在控制器内搜索任何类。 I dont want to have to add the version to the controller name as i want to make the revision updates as seamless as possible. 我不想将版本添加到控制器名称,因为我想使修订更新尽可能无缝。

我认为您可以通过向每个控制器添加路由前缀来解决此问题。

Can you use a URL query parameter? 可以使用URL查询参数吗?

https://localhost:8000/{controller}/{action}/{id}?version=?

You could then use control flow within the controller to determine what logic to use, based on the version. 然后,您可以使用控制器内的控制流,根据版本确定要使用的逻辑。

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

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