当前位置:首页 > Windows程序 > 正文

[翻译]ASP.NET Web API的路由

2021-05-25 Windows程序

原文:Routing in ASP.NET Web API

  在我们新建一个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){ } }

技术分享

    2.但是上面的约定只适用于GET、POST、PUT和DELETE方法。其他的HTTP方法可以使用AcceptVerbs attribute匹配,前面的四种方法亦同样适用。举例:

public class ProductsController : ApiController { [HttpGet] public Product FindProduct(id) {} }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71034.html