代码之家  ›  专栏  ›  技术社区  ›  katit

WebAPI按名称路由到控制器的特定方法

  •  0
  • katit  · 技术社区  · 6 年前

    这就是我现在所拥有的:一条路线和目前为止所有的控制器都证实了这一点,并且工作得很好。我们要保持原样。

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
                    name: "DitatApi",
                    routeTemplate: "api/{controller}/{action}"
    

    现在我们创建了新的控制器,但需要以不同的方式进行路由。下面是控制器代码以及如何路由这些方法。我如何设置这样的路线?

    public class CarrierController : ApiController
    {
        [HttpGet]
        public object Get(string id, int? key, string direction)
        {
            return null;
        }
    
        [HttpPost]
        public object Update()
        {
            return null;
        }
    
        [HttpDelete]
        public object Delete(int key)
        {
            return null;
        }
    
        [HttpGet]
        public object GenerateRandomObject(int randomParam)
        {
            return null;
        }
    }
    
    1. GET /api/carrier?id=<id>&key=<key>&direction=<direction>
    2. POST /api/carrier
    3. DELETE /api/carrier?key=<key>
    4. GET /api/carrier/random?randomParam=<random>
    1 回复  |  直到 6 年前
        1
  •  0
  •   Dalorzo    6 年前

    WebAPI v2介绍了 路由属性 这些可以与控制器类一起使用,并且可以方便地进行路由配置。

    例如:

     public class BookController : ApiController{
         //where author is a letter(a-Z) with a minimum of 5 character and 10 max.      
        [Route("html/{id}/{newAuthor:alpha:length(5,10)}")]
        public Book Get(int id, string newAuthor){
            return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
        }
    
       [Route("json/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
       public Book Get(int id, string newAuthor, string title){
           return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
       }
    ...
    

    但是,请注意查询参数 ?var1=1&var2=2 不接受评估以决定将使用哪种API方法。

    WebAPI 基于反射工作,因此,这意味着您的大括号变量在方法中必须匹配相同的名称。

    所以要匹配这样的东西 api/Products/Product/test 您的模板应该如下所示 "api/{controller}/{action}/{id}" 您的方法需要这样声明:

    [ActionName("Product")]
    [HttpGet]
    public object Product(string id){
       return id;
    }
    

    其中参数 string name 被替换 string id .