【问题标题】:How do I configure Web Api to select response format from url parameter?如何配置 Web Api 以从 url 参数中选择响应格式?
【发布时间】:2013-04-28 08:06:59
【问题描述】:

我正在尝试配置 web api 区域以允许我传递可选的格式扩展名。这是我的RegisterArea 方法的代码:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.Routes.MapHttpRoute(
        name: "Api_default",
        routeTemplate: @"Api/{controller}/{action}/{id}.{ext}",
        defaults: new
            {
                action = "Index",
                id = RouteParameter.Optional,
                formatter = RouteParameter.Optional
            },
        constraints: new
                            {
                                id = @"[0-9]+",
                                controller = @"[^\.]+",
                                ext = @"json|xml"
                            }
    );

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
            new UriPathExtensionMapping("json", "application/json")
        );

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
            new UriPathExtensionMapping("xml", "application/xml")
        );

}

现在,如果我去 http://www.example.com/api/countries 它工作正常,但是当我尝试 http://www.example.com/api/countries.json 时给了我

No type was found that matches the controller named 'countries.json'.

我做错了什么?

【问题讨论】:

    标签: .net asp.net-web-api asp.net-web-api-routing attributerouting


    【解决方案1】:

    找到问题了!上面的代码是正确的。但是,我正在使用 AttributeRouting,它在我的 App_Start 文件夹中添加了一个 AttributeRoutingHttpConfig.cs 并且把事情搞砸了。所以,如果你遇到这个问题,请检查一下!

    【讨论】:

    • 只是出于好奇,OP是什么意思?
    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2021-09-26
    • 2021-08-11
    • 2020-09-03
    相关资源
    最近更新 更多