UriPathExtensionMapping in MVC 4

二次信任 提交于 2019-12-06 13:35:21

问题


How do I use UriPathExtensionMapping in MVC4? I've added the mapping in the formatter such that:

MediaTypeMappings.Add(new UriPathExtensionMapping("json", new MediaTypeHeaderValue("application/json"))

But I can't use the extension on my route unless I add a verb, such as:

routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}.{extension}"

        );

Then it'll recognize my desired media type, but it also starts expecting "extension" as a parameter on the action. Example:

    public object Get(string extension)
    {
    }

Instead of just:

    public object Get()
    {
    }

How can I resolve this?

Thanks!


回答1:


I don't remember if I noticed this problem, but it might be because I explicitly specified the default value for the extension like:

var rF = routes.MapHttpRoute(
    name: "DefaultApi.v1.format",
    routeTemplate: "api/1/{controller}/{action}.{format}/{*id}",
    defaults: new { id = RouteParameter.Optional, format = "json", version = 1 }
);

*note format = "json" in the line beginning with defaults.

I did also notice that this sometimes doesn't work on requests with trailing parameters for id, like ~/api/1/values/get.json/4.




回答2:


I can't repro this problem.

You are right that, to use UriPathExtensionMapping, you will need to specify the {controller}.{ext} in your route, like what you described above. If you only specify the {controller}, and uri looks like ~/home.json, then the controller token will be mapped to home.json, which is probably not what you wanted.

However, you should not need to require an "extension" parameter in your action. If you continue seeing this problem, can you post your entire repro, including your controller, your routes and configuration set up with custom formatter? thank you.



来源:https://stackoverflow.com/questions/9520842/uripathextensionmapping-in-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!