我正在尝试使用ASP mvc构建REST API,我在路由方面遇到了一些麻烦。
我希望以一种简单方便的方式匹配以下网址:
https://foo.com/collections/
https://foo.com/collections.json/
https://foo.com/collections.xml/
https://foo.com/collections/collectionID/
https://foo.com/collections/collectionID.json/
https://foo.com/collections/collectionID.xml/
以后在同一模式上的更多项目:
https://foo.com/persons/
https://foo.com/persons.json/
https://foo.com/persons.xml/
https://foo.com/persons/personID/
https://foo.com/persons/personID.json/
https://foo.com/persons/personID.xml/
到目前为止,我最好的尝试是:
routes.MapRoute(
name: "RESTCollections",
url: "{controller}s/",
defaults: new { controller = "Collection", action = "Index" }
);
routes.MapRoute(
name: "RESTCollections",
url: "{controller}s/{format}/",
defaults: new { controller="Collection", action="Index", format = UrlParameter.Optional },
constraints: new { format = "json|xml|html" }
);
它设法匹配:
https://foo.com/collections/
https://foo.com/collections/json
但是我被困在那里试图替换控制器和格式之间的“/”给404.简单地删除“/”也给404.
答案 0 :(得分:0)
要回答您的问题,您可以尝试
`context.MapRoute(
"Api_default",
"{controller}/{action}.{format}",
new { controller = "Home", action = "Index", format = UrlParameter.Optional });`
如此处所述stackoverflow.com/.../customizing-asp-net-mvc-routing-to-service-json-xml-style-urls
另一方面,我不明白您为什么要说明要接受哪种格式发送到您的API。
您可以使用[FromBody] string content
将发送的值反序列化为方法。
或者您可以使用Route属性
定义参数的类型[Route("Post/{collection:string}")
public void Post(string collection)
如果string是预定义的约束,您可以创建自己的自定义约束。