【问题标题】:Error with WebApi RouteAttributeWebApi RouteAttribute 出错
【发布时间】:2017-10-23 11:15:47
【问题描述】:

这是我的前缀属性

 [RoutePrefix("news/farms")]
 public class farmsController : ApiController

我想删除基于 farmid 的行,但我想要这样的 url 结构

/news/farms/{farmId}?version={Version}

我尝试了如下代码的路由 url

 [HttpDelete, Route("{farmId}?version={Version}", Name = "Deletefarm")]

但它显示

The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.

请任何人告诉我是否有其他方法可以解决此错误?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    像你的例子一样设置RoutePrefix

    [RoutePrefix("news/farms")]
    public class FarmsController : ApiController
    

    还有你的删除方法:

    [HttpDelete]
    [Route("{farmId}")]
    public void Delete(int farmId, string version)
    

    那么这应该可以工作:

    .../news/farms/1?version=myVersion

    【讨论】:

      【解决方案2】:

      您为什么要尝试在路由中添加版本作为查询参数?这不是您想要的控制器路由吗?

      尽管如此: 这行得通吗?

      [HttpDelete]
      public async Task<IActionResult> Delete(int id, [FromQuery] string version)
      {
       //...your code
      }
      

      使用[FromQuery],您可以从...查询中指定您想要它;)

      【讨论】:

        【解决方案3】:

        URI 路径中不能有查询字符串,因此不允许,请参阅 - https://www.rfc-editor.org/rfc/rfc3986#section-3.3

        对于你的答案,你想要的是 -

        [HttpDelete]
        public IActionResult DeleteFarm(int farmId, [FromQuery] string version)
        {
            //
        }
        

        【讨论】:

          猜你喜欢
          • 2014-09-23
          • 2016-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-04
          • 2017-01-03
          • 1970-01-01
          • 2014-01-10
          相关资源
          最近更新 更多