草庐IT

c# - Web Api 2 API 无法识别路由的多个属性(版本控制)

coder 2024-06-02 原文

我正在尝试同时实现 Attribute Routing和来自 RoutingConstaints SampleVersionedRoute但是当我在 Controller 上同时使用两者时,versioned 属性不再有效。

我需要对属性进行哪些修改才能使其与属性路由配合使用?

对于代码示例,请下载示例项目(或者只查看上面链接中的几个文件),然后这样修改路由:

// When I use the RoutePrefix, VersionedRoute no longer works (Sending "Api-Version" through http header doesn't route correctly
// If I remove the RoutePrefix I can use VersionedRoute again
// What do I need to change in its code to be able to use both?

[VersionedRoute("api/Customers", 1)] // This route would be used as http://url/api/customers with a header of "api-version: 1"
[RoutePrefix("api/v1/Customers")] // This route would be used purely through url versioning of http://url/api/v1/Customers
public class CustomersV1Controller : ApiController {

    /* Other stuff removed */

    [VersionedRoute("api/Customer", 1)] // I'd rather not have to use this here at all and just use a single one on the class, but having both nor just one on either works right now.
    [Route("")]
    public IHttpActionResult Get()
    {
        return Json(_customers);
    }
}

VersionedRoute Code

VersionConstraint Code

编辑:如果您需要更多信息,甚至发布想法或要尝试的事情,请告诉我:)

Edit2:这是我尝试从 Troy Hunt 的博客中尝试做的事情的示例:http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html

Edit3:这是我希望编码尽可能接近的内容,因为它会减少大量开销和魔法字符串。

[VersionedRoute("api/Customers", 1)] // This route would be used as http://url/api/customers with a header of "api-version: 1"
[RoutePrefix("api/v1/Customers")] // This route would be used purely through url versioning of http://url/api/v1/Customers
public class CustomersV1Controller : ApiController {

    /* Other stuff removed */
    [Route("")]
    public IHttpActionResult Get()
    {
        // Removed
        return Ok(customers);
    }


    [Route("{id:int}")]
    public IHttpActionResult GetById(int id)
    {
        // Removed
        return Ok(customer);
    }
}

[VersionedRoute("api/Customers", 2)] // This route would be used as http://url/api/customers with a header of "api-version: 2"
[RoutePrefix("api/v2/Customers")] // This route would be used purely through url versioning of http://url/api/v2/Customers
public class CustomersV2Controller : ApiController {

    /* Other stuff removed */
    [Route("")]
    public IHttpActionResult Get()
    {
        // Removed
        return Ok(customersThatAreDifferentThanV1);
    }


    [Route("{id:int}")]
    public IHttpActionResult GetById(int id)
    {
        // Removed
        return Ok(customerThatIsDifferent);
    }
}

编辑:最后一点,尝试只在 Controller 属性级别而不是每个操作为每个路由写入一次路由版本信息。

最佳答案

RouteVersionedRoute 属性可以很好地协同工作,但是您的 RoutePrefix 属性也应用于您的 VersionedRoute(尝试访问/api/v1/Customers/api/Customer - 当设置了 api-version header 时,您将收到响应)

对于返回正确响应的示例中的两个 URL,以下代码将产生所需的行为,但显然这不能解决您想要一个 VersionedRoute 和一个 RoutePrefix 的问题 在类的顶部。为此需要另一种方法。但是,您可以为不同的 API 版本设置单独的 Controller 。

[RoutePrefix("api")]
public class CustomersV1Controller : ApiController
{
    /* Other stuff removed */

    [VersionedRoute("Customers", 1)]
    [Route("v1/Customers")]
    public IHttpActionResult Get()
    {
        return Json(_customers);
    }
}

一个改进是创建您自己的属性而不是 Route,这样您就不需要每次都为版本添加前缀:

public class CustomVersionedRoute : Attribute, IHttpRouteInfoProvider
{
    private readonly string _template;

    public CustomVersionedRoute(string route, int version)
    {
        _template = string.Format("v{0}/{1}", version, route);
    }

    public string Name { get { return _template; } }
    public string Template { get { return _template ; } }
    public int Order { get; set; }
}

[RoutePrefix("api")]
public class CustomersV2Controller : ApiController
{
    /* Other stuff removed */

    [VersionedRoute("Customers", 2)]
    [CustomVersionedRoute("Customers", 2)]
    public IHttpActionResult Get()
    {
        return Json(_customers);
    }
}

关于c# - Web Api 2 API 无法识别路由的多个属性(版本控制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307695/

有关c# - Web Api 2 API 无法识别路由的多个属性(版本控制)的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  9. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  10. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

随机推荐