WebAPI 2中的UriPathExtensionMapping

时间:2014-04-05 00:05:09

标签: c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

当我尝试向我的api添加扩展映射功能时,会发生奇怪的事情。有些东西有效,但我无法正确返回JSON。这些相关的问题让我无法前往:

我的项目启用了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中工作。帮助

1 个答案:

答案 0 :(得分: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";
    }
}