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] 标记方法。

  • 相关阅读:
    微信开发-如何自定义页面分享元素
    nginx实现日志按天切割
    JS兼容IE浏览器的方法
    mysql 索引过长1071-max key length is 767 byte
    playframework1.x的eclipse插件开源-playtools
    开放平台-web实现人人网第三方登录
    开放平台-web实现QQ第三方登录
    bash shell执行方式
    pushd和popd
    What do cryptic Github comments mean?
  • 原文地址:https://www.cnblogs.com/pengzhen/p/4901787.html
Copyright © 2011-2022 走看看