【问题标题】:How to set up routes correctly for webapi controller so id is picked up as part of url instead of querystring如何为 webapi 控制器正确设置路由,以便将 id 作为 url 的一部分而不是 querystring
【发布时间】:2020-08-04 09:21:49
【问题描述】:

我在获取 url 以正确解析我的控制器时遇到问题,方法是从 url 获取 id 而不是查询字符串参数。我有一个使用以下文件夹结构设置的 .net webapi 项目。

Root
  Controllers
    v1
      Partner
        CompaniesController
      PersonController
      QuoteController

如您所见,CompanyController 位于 Partner 文件夹中,而其他控制器位于 v1 文件夹中。我还在我的 CompaniesController 上使用 RoutePrefix,例如...

[EnableCors("*", "*", "*")]
[RoutePrefix("api/v1/partner/companies")]
public class CompaniesController : BaseApiController{

   [Route("contact")]
   [HttpPost]
   public IHttpActionResult Contact(string id)
   {
   }
}

我遇到的问题是以下网址返回 404。

https://localhost:44322/api/v1/partner/companies/contact/9da093ef-57a5-4da0-bd0e-5ac97cf304e2

但是下面的 url 可以正常工作并调用 find 方法

https://localhost:44322/api/v1/partner/companies/contact?id=9da093ef-57a5-4da0-bd0e-5ac97cf304e2

我认为这可能是我的 routeconfig 文件,所以我将其添加到其中,但仍然没有按预期运行。

routes.MapRoute(
    name: "Partner",
    url: "api/v1/partner/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

知道我需要更改哪些内容才能使用 id 作为 url 的一部分而不是查询字符串参数吗?

【问题讨论】:

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


    【解决方案1】:

    如果其他人遇到这种情况,我通过更改方法上的路由属性解决了这个问题。所以过去看起来像 [Route("contact")] 现在是 [Route("contact/{id}")]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      相关资源
      最近更新 更多