网页API版本配置 [英] Web API versioning configuration

查看:201
本文介绍了网页API版本配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的MVC和尝试写RESTful API,因此我使用的应用程序的网络API类型,并尝试建立版本,在最后我想有链接类​​型像API / V1 /价值/搞定,API / V2 /值/搞定。我试图创建控制器文件夹中的文件夹v1和v2,营造有一个名为Values​​Controller控制器,但我的要求是行不通的。我得到了HTTP 404.0 - 未找到。如何配置路由或做一些事情来决定这个问题?

I new in Mvc and try to write restful api, I use web api type of application, and try to create versioning, In final I would like to have link type like api/v1/values/get, api/v2/values/get. I tried to create folders v1 and v2 in controllers folder , and create there controllers with name ValuesController, but my request doesn't work. I got HTTP 404.0 - Not Found. How I can configure routing or do something to decide this problem?

推荐答案

通过命名空间API版本解释的此处。在博客文章并描述为自己创造一个新的HttpControllerSelector <一个href=\"http://aspnet.$c$cplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs\"相对=nofollow>给出的例子,然后切换到选择在一个FilterConfig 通过

API versioning through namespace is explained here. Create a new HttpControllerSelector for yourself as described in the blog post and given example, then switch to that selector in your FilterConfig via:

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));

然后,注册您的路线:

Then, register your routes:

config.Routes.MapHttpRoute(
  name: "VersionedApi",
  routeTemplate: "api/{version}/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

在自定义的 HttpControllerSelector ,如果要退回到一个默认版本,然后使用下列内容:

In your custom HttpControllerSelector, if you want to fallback to a default version, then use the following:

string versionName = GetRouteVariable<string>(routeData, "version");
versionName = versionName ?? DefaultVersion;

这篇关于网页API版本配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆