在ASP.NET MVC 4版本的Web API操作 [英] Versioning Web API actions in ASP.NET MVC 4

查看:132
本文介绍了在ASP.NET MVC 4版本的Web API操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序4。我想使用新的Web API功能对于学习的目的。我想学习如何公开相同的终点,而是提供不同的版本吧。换句话说,我要揭露类似如下的端点:

I have an ASP.NET MVC 4 app. I want to use the new Web API feature for learning purposes. I want to learn how to expose the same endpoint, but provide different versions of it. In other words, I want to expose endpoints like the following:

http://mysite/1.0/Products/1
http://mysite/2.0/Products/1

在试图做到这一点,我的默认控制器目录中增加了一个API目录。内的API目录下,我有两个其他的目录:Version1-0和Version2-0。每个这些目录中有一个名为ProductsController的一个ApiController。

In an attempt to do this, I added an "Api" directory within the default "Controllers" directory. Within the "Api" directory, I have two other directories: "Version1-0" and "Version2-0". Each of those directories has an ApiController named "ProductsController".

我试图通过我的WebApiConfig.cs文件中添加以下路由定义,露出端点:

I tried to expose the endpoints by adding the following route definition in my WebApiConfig.cs file:

config.Routes.MapHttpRoute(
  name: "1-0Api",
  routeTemplate: "api/1.0/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

不幸的是,我无法弄清楚如何公开通过我上面列出的URL行动。我究竟做错了什么?谢谢!

Unfortunately, I can't figure out how to expose actions via the URLs I listed above. What am I doing wrong? Thank you!

推荐答案

您可能正在运行到问题,因为控制器具有相同的名称。控制器命名空间或它在不事在所有的WebAPI,只有名称做的文件夹。我能想到的最简单的办法是重命名你的控制器ProductsV1Controller和ProductsV2Controller并设置两条路线指向你的控制器:

You're probably running into issues because the controllers have the same name. The controller namespace or the folder it's in doesn't matter at all to WebAPI, only the name does. The simplest thing I can think of is to rename your controllers ProductsV1Controller and ProductsV2Controller and set up two routes to point to your controllers:

config.Routes.MapHttpRoute(
    name: "1-0Api",
    routeTemplate: "api/1.0/Products/{id}",
    defaults: new { controller = "ProductsV1", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
    name: "2-0Api",
    routeTemplate: "api/2.0/Products/{id}",
    defaults: new { controller = "ProductsV2", id = RouteParameter.Optional }
);

当然,这个,如果你有你想要以这种方式暴露多个控制器变得混乱。让我看看我能不能想到的东西对你更好。

Of course, this gets messy if you have multiple controllers you want to expose in this way. Let me see if I can't think of something better for you.

这篇关于在ASP.NET MVC 4版本的Web API操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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