【问题标题】:UriPathExtensionMapping to control response format in WebAPIUriPathExtensionMapping 控制 WebAPI 中的响应格式
【发布时间】:2014-08-03 06:09:12
【问题描述】:

我在让 UriPathExtensionMapping 在 ASP.NET WebAPI 中工作时遇到问题。我的设置如下:

我的路线是:

            config.Routes.MapHttpRoute(
                name: "Api UriPathExtension",
                routeTemplate: "api/{controller}.{extension}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "Api UriPathExtension ID",
                routeTemplate: "api/{controller}/{id}.{extension}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

我的全球 ASAX 文件是:

    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

我的控制器是:

public IEnumerable<string> Get()
{
    return new string[] { "Box", "Rectangle" };
}

// GET /api/values/5
public string Get(int id)
{
    return "Box";
}

// POST /api/values
public void Post(string value)
{
}

// PUT /api/values/5
public void Put(int id, string value)
{
}

// DELETE /api/values/5
public void Delete(int id)
{
}

使用 curl 发出请求时,JSON 是默认响应,即使我明确请求 XML,我仍然会得到 JSON:

curl http://localhost/eco/api/products/5.xml

返回:

"http://www.google.com"

谁能看出我的设置有问题?

以下代码在配置路由后映射 Global.asax 文件中的扩展:

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

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

【问题讨论】:

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


    【解决方案1】:

    是否需要像这样注册扩展映射:

    config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("json", "application/json"));
    config.Formatters.XmlFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "application/xml"));
    

    发现示例here

    更新

    如果您查看 UriPathExtensionMapping 的代码,则扩展名的占位符是

    /// <summary>
    /// The <see cref="T:System.Uri"/> path extension key.
    /// </summary>
    public static readonly string UriPathExtensionKey = "ext";
    

    因此您的路线需要更改为({ext} 而不是 {extension}):

    config.Routes.MapHttpRoute(
                name: "Api UriPathExtension",
                routeTemplate: "api/{controller}.{ext}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    

    【讨论】:

    • 感谢您的回复,但是我已经有类似的代码来设置扩展映射(更新了问题)。但是,我确实将代码更改为您建议的代码,但它仍然无法正常工作。
    • @markpirvine - 好的,感谢您的澄清。查看我的更新,看看是否有帮助。
    • 非常感谢您抽出宝贵时间再次查看代码 - 我将“extension”形式更改为“ext”,它按预期工作。
    【解决方案2】:

    作为这个答案的附录,因为我还不能发表评论,你还应该确保你的 web.config 包含该行

    <modules runAllManagedModulesForAllRequests="true" />
    

    &lt;system.webServer&gt; 部分内。

    我的没有,这个例子对我不起作用,直到我添加了那行。

    【讨论】:

    • 虽然设置 runAllManagedModulesForAllRequests 会起作用,但它可能不是最佳选择,因为所有静态资源现在都将由所有 http 模块处理并会影响性能。最好将其关闭并添加一个强制所有 WebAPI URL 通过管道的 http 处理程序。我添加了以下内容以允许我的图像缓存 API 处理对 *.jpg 文件的请求&lt;add name="File handler for temp images" path="/api/imagecache/*" verb="GET" type="System.Web.Routing.UrlRoutingHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt;
    • 是的,我几乎对这种情况失去了希望,但您的解决方案再次让我幸免于难。谢谢
    猜你喜欢
    • 2018-02-26
    • 2015-01-11
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    相关资源
    最近更新 更多