真的遇到了麻烦与MVC路由交手,尽管上读到的博客和教程的负荷......MVC路由烦恼
我有这样的WebAPI功能:
public HttpResponseMessage UpsertProducts([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergProduct> heisenbergProducts)
和Route.config
默认路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
一切正常。
我现在已经添加了另一个功能:
public HttpResponseMessage ReviseInventory([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergReviseInventory> heisenbergReviseInventories)
尽管动作名称是不同的,似乎有冲突,并呼吁它们中的时,我得到一个500 internal server error
- 我猜它不知道哪一个使用。
我使用的URL美其名曰:
api/webapiproducts/upsertproducts?marketplaceId={0}&datasourceId={1}
我试图通过使用属性的路由来解决这个问题:
[Route("/api/WebApiProducts/upsertproducts/{marketplaceid}/{datasourceid}")]
public HttpResponseMessage UpsertProducts([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergProduct> heisenbergProducts)
和
[Route("/api/WebApiProducts/reviseinventory/{marketplaceid}/{datasourceid}")]
public HttpResponseMessage ReviseInventory([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergReviseInventory> heisenbergReviseInventories)
既不是我的路由属性似乎工作。我在做什么错了,我在这里不理解路由?
正如@Nkosi指出,我会把错误的路径文件!这里是我的WebApiConfig.cs内容:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
你是正确的 - 我加了错误的配置文件contect - 我已经更新的问题有正确的数据。尽管使用我的查询字符串参数仍然有问题。我设法通过更改我打电话的网址来实现它 - 我认为你可以采取两种方式。看到我的回答 – Rick
@瑞克。他们可以同时工作。映射路由的顺序非常重要,因为第一条路由匹配获胜,首先映射更具体的路由,后面映射更多的通用路由。您需要通过将最后一个映射向上一个来切换顺序。它没有达到第二条基于常规的路线,因为它已经与第一条路线相匹配。 – Nkosi
谢谢,是的,你对订购是正确的 - 我忘了它。我改变了顺序并尝试使用querystring方法调用,但它仍然无法工作。我似乎仍然必须使用我在答案中提出的方法。 – Rick