簡體   English   中英

WebApi路由:api / {controller} / {id}和api / {controller} / {action}同時

[英]WebApi Routing: api/{controller}/{id} and api/{controller}/{action} at the same time

我有默認的webapi路由配置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
);

我想支持以下場景:

//api/mycontroller
public IQueryable<MyDTO> Get();

//api/mycontroller/{id} where id can be anything except "customaction1" and "customaction2"
public HttpResponseMessage Get(string id);

//api/mycontroller/customaction
[HttpPost]
public void CustomAction1([FromBody] string data);
[HttpPost]
public void CustomAction2([FromBody] string data);

我試圖將[Route("api/mycontroller/customaction1")]應用於CustomAction1方法,類似於CustomAction2但得到:

找到了與請求匹配的多個操作:類型為MyProject.WebApiService.MyController的類型MyProject.WebApiService.MyController CustomAction2上的CustomAction1

確保已將屬性路由配置為默認配置

//....
config.MapHttpAttributeRoutes()

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
);
//....

如果要對out屬性路由執行相同操作,則需要顯式配置路由

//This one constrains id to be an int
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { action="Get", id = RouteParameter.Optional },
    constraints : new { id = @"\d" }
);
//This one should catch the routes with actions included
config.Routes.MapHttpRoute(
    name: "ActionRoutes",
    routeTemplate: "api/{controller}/{action}"
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM