在我们新建一个Web API项目时,会在App_Start文件夹下的WebApiConfig.cs中定义一个默认路由:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
在默认路由中加入“api”是为了避免与ASP.NET MVC的路由冲突。当然如果你不喜欢这个约定,可以修改默认路由。
路由匹配规则:{controller}和{id}略过,只介绍action的匹配。
1.Web API首先根据HTTP方法名寻找命名以HTTP方法名开头的action。举例:
public class ProductsController : ApiController
{
public void GetAllProducts() { }
public IEnumerable<Product> GetProductById(int id) { }
public HttpResponseMessage DeleteProduct(int id){ }
}
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAApgAAADfCAIAAADdkTRjAAAZVklEQVR4nO2cMZKjPBOG9yzUv7exDjMzxUV2qhxwjQkm4RROHJFsbX35Zpv5D2xAEk2DwcZt9/OUa8vGDWLR2/0iCc+Pv+CJ33/+e/QpgEUQBuigEMv8ePQJwKaQjSCCMEAHhVgGI/cF2QgiCAN0UIhlMHJfkI0ggjBAB4VYBiP3BdkIIggDdFCIZTByX5CNIIIwQAeFWAYj9wXZCCIIA3RQiGUwcl+QjSCCMEAHhVgGI/cF2QgiCAN0UIhlMHJfkI0ggjBAB4VYBiP3BdkIIggDdFCIZTByX5CNIIIwQAeFWAYj9wXZCCIIA3RQiGVe2Mi/3n6GX4ft9zXNc2bjy3aHHbYVxtfbz59vXxs2CKt5ztLhhWuNfFhSz1sOv8LP//1MX+H9Tdj4efj79dZvEQv019vPn/97lxL9631kl+HpYeQCS7NxrN///k16s+vQTg9ZL052vdjiy3aHHVaW6a/3kYSNQujEp2ZF6ZiZ8vfj9bV3KyNXArSYw2f4X/gcXOGvt59hF4bHOfwK4naxIYxc4D5GHn319d6a94QSRrpebPFlu8MOq4z88LkL729Bd3I68blZXzqmUv5+vL72HmzkSvzbe8ju8Q+fYff5GcV3w77w6/D37+Fz1936vX9djvx12biL9PP1Hk8P/B1uT1t5Ke5u5KPbh8eJ3n+9d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+IE8f2uhu+YZngo+vAyO3zI2M/F/24/B4/nz0C4x8e1YshY48Ll5ljwuf+tKbF86p+FMSKj213p9GWafj/vzcsuDoc1mPPxTvl/VT62PDYP2RdWViPfLfS1fVyfPx/SG7JoSpG2EyHpaAkVuGv+zmi5tm48S89GBBlHlsu9zkYTfDPMt52gUjtwxG7osNjXzycTMwxKo/MGB9cUKe1IerwMgtg5H7YssR+ep42A7KNOigEMtg5L4gG0EEYYAOCrEMRu4LshFEEAbooBDLYOS+IBtBBGGADgqxDEbuC7IRRBAG6KAQy2DkviAbQQRhgA4KsQxG7guyEUQQBuigEMtg5L4gG0EEYYAOCrEMRu4LshFEEAbooBDLYOS+IBtBBGGADgqxDEbuC7IRRBAG6KAQy2DkviAbQQRhgA4KsQxG7guyEUQQBuigEMv8H0Oh9V423VjyAAAAAElFTkSuQmCC" alt="" />
2.但是上面的约定只适用于GET、POST、PUT和DELETE方法。其他的HTTP方法可以使用AcceptVerbs attribute匹配,前面的四种方法亦同样适用。举例:
public class ProductsController : ApiController
{
[HttpGet]
public Product FindProduct(id) {}
}
public class ProductsController : ApiController
{
[AcceptVerbs("GET", "HEAD")]
public Product FindProduct(id) { } // WebDAV method
[AcceptVerbs("MKCOL")]
public void MakeCollection() { }
}
3.根据action名匹配(重写路由)。举例:
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
3.1.根据上面的路由规则“api/products/details/1”的GET请求将会匹配:
public class ProductsController : ApiController
{
[HttpGet]
public string Details(int id);
}
3.2.可以使用ActionName attribute重写action名。举例:
public class ProductsController : ApiController
{
[HttpGet]
[ActionName("Thumbnail")]
public HttpResponseMessage GetThumbnailImage(int id); [HttpPost]
[ActionName("Thumbnail")]
public void AddThumbnailImage(int id);
}
这样"api/products/thumbnail/id”就有两个匹配,分别对应GET和POST。
4.如果一个方法不想被当作action调用,可以使用NonAction attribute,举例:
// Not an action method.
[NonAction]
public string GetPrivateData() { ... }