UriPathExtensionMapping in WebAPI 2

本文关键字:WebAPI in UriPathExtensionMapping | 更新日期: 2023-09-27 17:56:39

当我尝试向我的 API 添加扩展映射功能时,发生了奇怪的事情。有些事情可以工作,但我无法获得任何正确返回 JSON 的内容。这些相关问题并没有让我去我需要去的地方:

  • UriPathExtensionMapping,用于控制 WebAPI 中的响应格式
  • MVC 4 中的 UriPathExtensionMapping

我的项目同时启用了 HttpRoutes 和 HttpAttributeRoutes。不确定这是否重要 - 我只是使用默认的 WebApi 项目模板。我有以下路线:

// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
    name: "Api UriPathExtension",
    routeTemplate: "api/{controller}.{ext}",
    defaults: new { }
);
config.Routes.MapHttpRoute(
    name: "Api UriPathExtension ID 1",
    routeTemplate: "api/{controller}.{ext}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
   name: "Api UriPathExtension ID 2",
    routeTemplate: "api/{controller}/{id}.{ext}",
    defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

这是我的控制器:

[RoutePrefix("api/roundTypes")]
public class RoundTypesController : ApiController
{
    // GET api/roundTypes
    [Route("")][HttpGet]
    public IQueryable<Vcijis.RoundType> GetAllRoundTypes()

当我测试它时:

http://localhost/api/roundTypes **works** but is XML
http://localhost/api/roundTypes/ **works**  (also XML)
http://localhost/api/roundTypes.json returns **404**
http://localhost/api/roundTypes.json/ returns a **JSON formatted error**

我收到的 JSON 错误消息是:

{"message":"No HTTP resource was found that matches the request URI 
'http://localhost/api/roundTypes.json/'.",
"messageDetail":"No action was found on the controller 'RoundTypes' 
that matches the request."}

我也尝试过使用 id 参数并得到类似的结果。我似乎根本无法让 {ext} 在 HttpAttributeRoutes 中工作。帮助?

UriPathExtensionMapping in WebAPI 2

无法从与传统路由匹配的路由访问属性控制器/操作。因此,您需要使用属性路由来指定路由模板中的{ext}

举个例子:

[RoutePrefix("api/customers")]
public class CustomersController : ApiController
{
    [Route("~/api/customers.{ext}")]
    [Route]
    public string Get()
    {
        return "Get All Customers";
    }
    [Route("{id}.{ext}")]
    [Route("{id}")]
    public string Get(int id)
    {
        return "Get Single Customer";
    }
    [Route]
    public string Post(Customer customer)
    {
        return "Created Customer";
    }
    [Route("{id}")]
    public string Put(int id, Customer customer)
    {
        return "Updated Customer";
    }
    [Route("{id}")]
    public string Delete(int id)
    {
        return "Deleted Customer";
    }
}