【问题标题】:mvc api routing with variable to save basic path带有变量的mvc api路由以保存基本路径
【发布时间】:2018-02-12 08:14:38
【问题描述】:

我在一个 mvc Api 项目中工作,在使用 [route("api/MyCont/getspecific")] 路由操作时,我意识到 使用一个变量来存储这个控制器的基本路径是个好主意:“api/myCont”,这样我就可以重用这部分路由,也可以使代码的维护更容易。

这是我尝试过的:

 public class MyContController : ApiController
{

    private readonly string BaseRoute="api/MyCont" ;

    [HttpGet]
    [Route(BaseRoute+"/GetSpecific")]
    public IHttpActionResult GetSpecificItem( string ItemId)
    {
    /* do something
     get the item from a source
    */

      return Ok(Item);
    }

}

但是当我这样做时,路由中出现错误“非静态字段、方法或roperty BaseRoute需要对象引用”。

我应该怎么做才能修复它? 就良好做法而言,您认为我正在做的事情是个好主意吗?

【问题讨论】:

标签: c# asp.net-mvc routing


【解决方案1】:

使用下面的代码,你使用它的变量应该是静态的,因为在 rout 表中注册 Rout 时,应该评估表达式。

        private const string BaseRoute = "api/MyCont";
        [HttpGet]
        [Route(BaseRoute + "/GetSpecific")]
        public string Helloworld()
        {
            return "Hello World";
        }

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2020-08-30
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多