ASP.NET Web API Model-ParameterBinding

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   使用   ar   

ASP.NET Web API Model-ParameterBinding前言

通過上個篇幅的學習瞭解Model綁定的基礎知識,然而在ASP.NET Web API中Model綁定功能模組並不是被直接調用的,而是要通過本篇要介紹的內容ParameterBinding的一系列對象對其進行封裝調用,通過本篇的學習之後也會大概的清楚在Web API中綁定會有哪幾種方式。

 

Model-ParameterBinding(對象篇)

在ASP.NET Web API中ParameterBinding代表著參數綁定並且在這其中涉及了幾種綁定的方式,然而ParaMeterBinding並不是單獨執行的,就好比一個控制器方法中有可能會有多個參數一樣,所以我們就先來看一下ActionBinding的相關對象,對於這些對象的產生的環境以及過程我們在後面的篇幅中會有講解。

 

HttpActionBinding

代碼1-1

namespace System.Web.Http.Controllers{    public class HttpActionBinding    {        public HttpActionBinding();        public HttpActionBinding(HttpActionDescriptor actionDescriptor, HttpParameterBinding[] bindings);        public HttpActionDescriptor ActionDescriptor { get; set; }        public HttpParameterBinding[] ParameterBindings { get; set; }        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken);    }}

代碼1-1中對於HttpActionBinding類型的定義一目瞭然,看HttpActionBinding類型的重載建構函式中有HttpActionDescriptor類型、HttpParameterBinding類型的數群組類型作為參數,HttpActionDescriptor類型作為控制器方法描述類型大家已經很熟悉了吧,這個類型中包含著控制器方法的中繼資料資訊,而後者HttpParameterBinding類型則是表示著參數綁定對象,其實在Model綁定中每個參數的綁定都是通過ParameterBinding來綁定的,所以這裡的執行過程我們暫時不去深入瞭解,就是單純的瞭解一下相關的物件模型。

 

HttpParameterBinding

代碼1-2

namespace System.Web.Http.Controllers{    public abstract class HttpParameterBinding    {        protected HttpParameterBinding(HttpParameterDescriptor descriptor);        public HttpParameterDescriptor Descriptor { get; }        public virtual string ErrorMessage { get; }        public bool IsValid { get; }        public virtual bool WillReadBody { get; }        public abstract Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken);        protected object GetValue(HttpActionContext actionContext);        protected void SetValue(HttpActionContext actionContext, object value);    }}

在代碼1-2中我們看到HttpParameterBinding類型的定義,可以看到HttpParameterBinding是抽象類別型,並且實現綁定的方法ExecuteBindingAsync()也是抽象的,這也是為了在不同的環境和情況相愛採取不同的綁定機製做好鋪墊就是多態啦,這個我們後面會說,我們還是先看下HttpParameterBinding類型的內部定義,首先我們看到的是建構函式中的參數類型,HttpParameterDescriptor類型,又是一個對象描述類型,這次的描述對象則是控制其方法中的某個參數,而HttpParameterBinding對象執行個體的產生則是根據HttpParameterDescriptor對象執行個體而來,這個後續的篇幅中會有講解。ErrorMessage屬性工作表示在ParameterBinding綁定的過程中出現的錯誤資訊,而IsValid屬性工作表示綁定是否可以完成的依據就是判斷ErrorMessage屬性是否為Null,WillReadBody屬性工作表示ParameterBinding對象是否讀取Http訊息本文內容作為參數繫結資料源,這個稍後給大家看的樣本中就有,一看便知。GetValue()和SetValue()方法就是向當前HttpActionContext中擷取對應的參數值和設定參數對應值。

 

ModelBinderParameterBinding

代碼1-3

namespace System.Web.Http.ModelBinding{    public class ModelBinderParameterBinding : HttpParameterBinding, IValueProviderParameterBinding    {        public ModelBinderParameterBinding(HttpParameterDescriptor descriptor, IModelBinder modelBinder, IEnumerable<System.Web.Http.ValueProviders.ValueProviderFactory> valueProviderFactories);        public IModelBinder Binder { get; }        public IEnumerable<System.Web.Http.ValueProviders.ValueProviderFactory> ValueProviderFactories { get; }        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken);    }}

代碼1-3表示的是ModelBinderParameterBinding類型,這個類型代表的綁定方式(繫結資料來源)是通過IModelBinder來擷取的,也就正如代碼1-3中我們看到的建構函式一樣,其中有IModelBinder和ValueProviderFactory類型的集合,這些就是資料繫結的資料來源。Binder屬性和ValueProviderFactories屬性也就是建構函式傳入的兩個類型值。對於綁定的細節這裡就不說多了。

 

FormatterParameterBinding

代碼1-4

namespace System.Web.Http.ModelBinding{    public class FormatterParameterBinding : HttpParameterBinding    {        public FormatterParameterBinding(HttpParameterDescriptor descriptor, IEnumerable<MediaTypeFormatter> formatters, IBodyModelValidator bodyModelValidator);        public IBodyModelValidator BodyModelValidator { get; set; }        public override string ErrorMessage { get; }        public IEnumerable<MediaTypeFormatter> Formatters { get; set; }        public override bool WillReadBody { get; }        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken);        public virtual Task<object> ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger);    }}

代碼1-4中所示的FormatterParameterBinding類型是通過哪種方式來擷取綁定資料來源的呢?大家可以看到WillReadBody屬性在這個類型中被重寫了,原來在HttpParameterBinding類型中預設為false的是不會對Http請求的本文內容進行讀寫的,而這裡在FormatterParameterBinding類型中,已然的重寫了,說明在這個類型中我們所能用到的綁定資料來源就是從Http請求的本文內容來讀取了,然而Http請求的本文內容並不是直接放在那裡供我們讀取的,而是在用戶端發送前就已經被指定的序列化器序列化了。

那麼我們在伺服器端就要還原序列化才能擷取到值,這裡在代碼1-4中我們看到建構函式中可以看到和代碼1-3一樣都是具有一個HttpParameterDescriptor類型的參數對象,而後則是一個MediaTypeFormatter類型的集合對象,最後是進行Model驗證的對象,這個後續再說。

現在我們就來看看第二個參數類型中的MediaTypeFormatter類型。

 

MediaTypeFormatter

代碼1-5

namespace System.Net.Http.Formatting{    public abstract class MediaTypeFormatter    {        protected MediaTypeFormatter();        public abstract bool CanReadType(Type type);        public abstract bool CanWriteType(Type type);        public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger);        public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext);    }}

在代碼1-5中所示的MediaTypeFormatter類型是被刪減過的一部分,所剩4個方法中兩個是抽象方法兩個是虛方法,先看兩個抽象方法的定義,CanReadType()方法表示的是根據指定的參數類型從當前的Http請求本文中能否讀取到改類型的值,簡單來說就是能否把本文內容還原序列化為指定的參數類型,同理CanWriterType()是對響應本文進行操作判斷。而ReadFromStreamAsync()方法和WriteToStreamAsync()方法則是對Http請求本文內容和Http響應本文內容進行實際操作的兩個方法。

對於MediaTypeFormatter類型的實作類別型比如說針對Json格式的JsonMediaTypeFormatter和針對Xml格式的XmlMediaTypeFormatter.

我們看一下JsonMediaTypeFormatter類型的簡單樣本,大家就會知道是怎麼回事了。

首先我們在伺服器端的控制器中定義一個接收Post請求的方法,

代碼1-6

        [CustomControllerActionAuthorizationFilter]        public void Post(Product product)        {            products.Add(product);        }

為了方便示範在其控制其方法上加了個授權過濾器,然後我們對Post請求的處理使用JsonMediaTypeFormatter類型進行還原序列化的操作將在CustomControllerActionAuthorizationFilter過濾器類型中進行。

代碼1-7

public Task<System.Net.Http.HttpResponseMessage> ExecuteAuthorizationFilterAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<System.Net.Http.HttpResponseMessage>> continuation)        {            Console.WriteLine(actionContext.Request.Content.Headers.ContentType.MediaType);            IEnumerable<MediaTypeFormatter> formatters = new MediaTypeFormatter[]             {                new JsonMediaTypeFormatter()            };            Product product = actionContext.Request.Content.ReadAsAsync<Common.Product>(formatters).Result;            Console.WriteLine(product.ProductID);            Console.WriteLine(product.ProductName);            Console.WriteLine(product.ProductCategory);            return continuation();        }

在代碼1-7中,在請求到達控制器方法之前會先經過授權過濾器,在這其中首先我們是先向伺服器端的控制器輸出了當前請求的格式類型,然後就對當前請求的本文內容使用JsonMediaTypeFormatter類型進行還原序列化操作。

我們再看下用戶端使用HttpClient類型進行類比Post請求,

代碼1-8

            HttpClient httpClient = new HttpClient();            Product product = new Product()            {                ProductID = "003",                ProductName = "旺仔牛奶",                ProductCategory = "食品類"            };            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/api/product", product);

最後結果1.

圖1

看到這裡想必大家也知道對於XmlMediaTypeFormatter的使用方式是怎樣的了。

還有一種MediaTypeFormatter類型FormUrlEncodedMediaTypeFormatter類型,FormUrlEncodedMediaTypeFormatter類型表示的是在Http Post請求中表單提交的資料所用格式器,我們看一下FormUrlEncodedMediaTypeFormatter類型中CanReadType()方法的實現。

代碼1-9

    public override bool CanReadType(Type type)    {        if (type == null)        {            throw Error.ArgumentNull("type");        }        if (!(type == typeof(FormDataCollection)))        {            return FormattingUtilities.IsJTokenType(type);        }        return true;   }

在代碼1-9我們可以看到FormDataCollection類型實際就是IEnumerable<KeyValuePair<string, string>>類型的對象,在表單提交後的請求Url中大家也都可以看到是是key=value的形式,所以這裡就是這種格式的。對於這個格式器的樣本會在後面的篇幅給大家做示範講解。

 

HttpRequestParameterBinding

最後我們再看一個RequestParameterBinding對象。

代碼1-10

    public class HttpRequestParameterBinding : HttpParameterBinding    {        // Methods        public HttpRequestParameterBinding(HttpParameterDescriptor descriptor)            : base(descriptor)        {        }        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)        {            string parameterName = base.Descriptor.ParameterName;            HttpRequestMessage request = actionContext.ControllerContext.Request;            actionContext.ActionArguments.Add(parameterName, request);            return TaskHelpers.Completed();        }    }

在代碼1-10中我們看到再ExecuteBindingAsync()方法的實現中,是直接擷取到參數名稱和當前的請求對象,然後添加到控制其方法執行內容的ActionArguments屬性中,在之前的篇幅中也說過這個屬性用來存放方法對應參數值(Model綁定後的值)。

本篇關於ParameterBinding的對象介紹就到這裡,都是零零散散的不過在後面的篇幅中都會有樣本介紹說明的。

 

 

 

金源

出處:http://www.cnblogs.com/jin-yuan/

本文著作權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面

ASP.NET Web API Model-ParameterBinding

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.