Response format specification in ASP.NET MVC 3 Routes
I'm creating an API for a website. I'm using ASP.Net MVC 3 and I'm trying to create routes that support an optional .format parameter. So the client app could request /user/post.json, /user/posts.xml or just /users/posts I was able to make the .json or .xml ending url's work using the following route:
routes.MapRoute( _
"no_params", _
"{controller}/{action}.{format}", _
New With {.action = "Index", .format = UrlParameter.Optional} _
)
But I couldn't make the url without the .format parame开发者_如何学Pythonter (/user/posts) work alongside. Can anyone help me out here with some example?
thanks!
Firstly I would say that the client can specify the type using 'content-type' rather than on the url :)
But to get it working you will need to register another route without the format since using /user/posts does not contain a period (.) it cannot match the route you specified.
routes.MapRoute("no_params_no_format", "{controller}/{action}", _
New With {.action = "Index" } _
)
HTH
Just remove the dot:
routes.MapRoute( _
"no_params", _
"{controller}/{action}{format}", _
New With {.action = "Index", .format = UrlParameter.Optional}, _
New With {.format = "(\.json|\.xml)?"} _
)
精彩评论