WebApi學習筆記

來源:互聯網
上載者:User

標籤:

1、與mvc區別:
    (1)controller繼承自ApiController    
    (2)action不返回視圖而是返回資料
    (3)訪問:http://localhost:1671/api/products/(productscontroller)

2、瀏覽器訪問結果區別
    (1)Firefox、Google返回xml
     (2)IE返回json包
     原因:出現這種差別的原因是IE和Firefox發送了不同的Accept前序,因此,Web API在響應中發送了不同的內容類型
    
3、解決循環參考
    (1)App_Start檔案夾,並開啟名為WebApiConfig.cs的檔案
        // 新代碼:把JSON格式化器設定為防止對象引用,並把XML格式化器從管線(指HTTP的請求處理管線)中完全刪除
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        
4、Authorization
    (1)MVC和Web API都定義了Authorize註解屬性,但位於不同的命名空間。MVC使用的是System.Web.Mvc.AuthorizeAttribute,而Web API使用System.Web.Http.AuthorizeAttribute
    
5、Knockout.js
    (1)是一個JavaScript庫,它讓HTML控制項很容易與資料進行綁定。Knockout.js使用的是“模型-視圖-視圖模型(MVVM)”模式
    
6、ApiExplorer類
    (1)為Web API建立協助頁面
    (2)vs2013需要引用System.Net.Http 4.0.0.0 並在Areas/view/web.config中修改: <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    
7、通過.NET用戶端調用Web API
    (1)安裝Web API用戶端庫:通過NuGet :Install the Web API Client Libraries
    (2)建立一個新的HttpClient執行個體
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:9000/");
        
        // 為JSON格式添加一個Accept前序
        client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
    (3)具體CURD操作:http://www.cnblogs.com/r01cn/archive/2012/11/20/2779011.html
    (4)// 列出所有產品
        HttpResponseMessage response = client.GetAsync("api/products").Result;  // Blocking call(阻塞調用)!
        //採用Result屬性的過程是應用程式線程阻塞的。控制台應用程式的阻塞沒問題,但是,你決不應該在一個Windows應用程式的UI上做這種事,因為這會阻塞UI去響應使用者的輸入

8、HttpClient訊息處理器
    (1)在用戶端,HttpClient類使用訊息處理器處理請求。預設的處理器是HttpClientHandler,它在網路上發送請求,並從伺服器擷取響應。你可以把自訂訊息處理器插入到這種用戶端管線之中.
    (2)要編寫自訂訊息處理器,需從System.Net.Http.DelegatingHandler進行派生,並重寫SendAsync方法
        class MessageHandler1 : DelegatingHandler
        {
            private int _count = 0;
            protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                _count++;
                request.Headers.Add("X-Custom-Header", _count.ToString());
                return base.SendAsync(request, cancellationToken);
            }
        }
    (3)要將自訂處理器添加到HttpClient,需使用HttpClientFactory.Create方法:HttpClient client = HttpClientFactory.Create(new Handler1(), new Handler2(), new Handler3());
    (4)要在伺服器端添加訊息處理器,需要將該處理器添加到HttpConfiguration.MessageHandlers集合。如果建立項目用的是“ASP.NET MVC 4 Web應用程式”模板,你可以在WebApiConfig類中做這件事:
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "Route2",
                    routeTemplate: "api2/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional },
                    constraints: null,
                    handler: new MessageHandler2()  // per-route message handler(單路由訊息處理器)
                );

                config.MessageHandlers.Add(new MessageHandler1());  // global message handler(全域訊息處理器)
            }
        }
    (5)具體參見:http://www.cnblogs.com/r01cn/archive/2012/11/22/2781707.html
    
9、WebApi路由
    (1)Web API的預設路由模板是“api/{controller}/{id}”。在這個模板中,“api”是一個文字式路徑片段,而{controller}和{id}則是預留位置變數.
    (2)/api/contacts
        /api/contacts/1
        /api/products/gizmo1
    (3)路由變異
        替代用於HTTP方法的命名規範,可以明確地為一個動作指定HTTP方法,這是通過以HttpGet、HttpPut、HttpPost或HttpDelete註解屬性對動作方法進行修飾來實現的.
    (4)具體參見:http://www.cnblogs.com/r01cn/archive/2012/11/23/2784224.html
    
10、ASP.NET Web API中的異常處理
    (1)異常過濾器實現System.Web.Http.Filters.IExceptionFilter介面。編寫異常過濾器最簡單的方式是通過System.Web.Http.Filters.ExceptionFilterAttribute類進行派生,並重寫其OnException方法.
    (2)以下是將NotImplementedException(沒有實現介面或抽象類別要求的方法時,出現的異常)異常轉換成HTTP狀態代碼“501 — 未實現”的一個過濾器:
        public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute  
        {
            public override void OnException(HttpActionExecutedContext context)
            {
                if (context.Exception is NotImplementedException)
                {
                    context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                }
            }
        }
    (3) 使用方式:
        [NotImplExceptionFilter]
        public Contact GetContact(int id)
        
        [NotImplExceptionFilter]
        public class ProductsController : ApiController
        
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());
        
                // Other configuration code(其它配置代碼)...
            }
        }
    (4)具體參見:http://www.cnblogs.com/r01cn/archive/2012/12/04/2801664.html
    
    
11、ASP.NET Web API批處理器(不太瞭解)    

12、ASP.NET Web API中的HTTP Cookie
    (1)具體參見:http://www.cnblogs.com/r01cn/archive/2013/05/16/3081108.html
    
13、媒體格式化器(JSON和XML)
    (1)可以自訂返回的資料格式
    (2)具體參見:http://www.cnblogs.com/r01cn/archive/2013/05/17/3083400.html

14、ASP.NET Web API中的JSON和XML序列化
    (1)參見:http://www.cnblogs.com/r01cn/p/3155653.html
    
15、模型驗證
    (1)參見:http://www.cnblogs.com/r01cn/p/3193095.html

WebApi學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.