zoukankan      html  css  js  c++  java
  • web api :Routing in ASP.NET Web API

     

    Web API 和SignalR都是在服务层。

    If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing.

    The main difference is that Web API uses the HTTP method, not the URI path, to select the action.(web api和mvc路由最主要的区别是,mvc是使用URI路径来选择action的,而web api 则是使用http方法来选择action的。)

    You can also use MVC-style routing in Web API. This article does not assume any knowledge of ASP.NET MVC.

    参考官网:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

    1.路由表

    1.1默认配置

    默认的路由映射,所以,调用api的时候,必须以api开头

    1. routes.MapHttpRoute(
    2.     name: "API Default",
    3.     routeTemplate: "api/{controller}/{id}",
    4.     defaults: new { id = RouteParameter.Optional }
    5. );

    eg:

    • /api/contacts
    • /api/contacts/1
    • /api/products/gizmo1

    而 /contacts/1就不会成功。

    1.2默认约定

    默认的约定,以Get,Delete,Put,Post这些开头的方法:

    1. public class ProductsController : ApiController
    2. {
    3.     public void GetAllProducts() { }
    4.     public IEnumerable<Product> GetProductById(int id) { }
    5.     public HttpResponseMessage DeleteProduct(int id){ }
    6. }

    HTTP Method

    URI Path

    Action

    Parameter

    GET

    api/products

    GetAllProducts

    (none)

    GET

    api/products/4

    GetProductById

    4

    DELETE

    api/products/4

    DeleteProduct

    4

    POST

    api/products

    (no match)

      

    2.路由变量

    2.1 Http方法

    使用HttpGet, HttpPut, HttpPost, or HttpDelete 来进行标记方法。

    也可以使用[AcceptVerbs("GET", "HEAD")]来标记多个选择。

    2.2使用ActionName来路由

    1. routes.MapHttpRoute(
    2.     name: "ActionApi",
    3.     routeTemplate: "api/{controller}/{action}/{id}",
    4.     defaults: new { id = RouteParameter.Optional }
    5. );

    则以上的配置可以支持两种:

    One is

    1. public class ProductsController : ApiController
    2. {
    3.     [HttpGet]
    4.     public string Details(int id);
    5. }

    The other is:(api/products/thumbnail/id

    1. public class ProductsController : ApiController
    2. {
    3.     [HttpGet]
    4.     [ActionName("Thumbnail")]
    5.     public HttpResponseMessage GetThumbnailImage(int id);
    6.  
    7.     [HttpPost]
    8.     [ActionName("Thumbnail")]
    9.     public void AddThumbnailImage(int id);
    10. }

    2.3非Action

    使用[NonAction] 标记方法。

  • 相关阅读:
    vue-router 实践
    修改vue中<router-link>的默认样式
    JSON.parse() 与 JSON.stringify() 的区别
    JS 中的异步操作
    CSS3 box-sizing:border-box的好处
    element ui 栅格布局
    css overflow用法
    koa中间件机制
    canvas 入门
    前端面试题:淘宝首页用了多少种标签
  • 原文地址:https://www.cnblogs.com/pengzhen/p/4901787.html
Copyright © 2011-2022 走看看