標籤:
翻譯自:http://www.c-sharpcorner.com/article/parameter-binding-in-asp-net-web-api/
主要自己學習下,說是翻譯,主要是把文章的意思記錄下,下面進入正題
web api 對於一般的基本類型(primitive type)(bool,int ,double,log,timespan,datetime,guid,string)直接從url讀取,對於複雜類型,web api從請求的body擷取,需要使用media type。
對於這個api:
Public HttpResponseMessage Put(int id, Employee employee) { … … }
View Code
web api 從url中擷取id類型,從body中擷取employee類型。
當然這是預設情況,我們可以強制web api通過fromurl和frombody特性從url或者從body擷取。
fromuri 特性
public class TestData { public string Name { get; set; } public int Id { get; set; } }
View Code
public HttpResponseMessage Get([FromUri] TestData data) {…… return Request.CreateResponse(HttpStatusCode.OK, true); }
View Code
這樣就可以強制從url擷取參數,web api產生TestData類。url:http://localhost:24367/api/Employee?Name=Jignesh&Id=10
可以測試下,這樣沒任何問題。
fromBody 特性
[HttpPost] public HttpResponseMessage Post([FromBody] string name) { …… return Request.CreateResponse(HttpStatusCode.OK, true); }
View Code
對於這個api,調用時要設定content type:“application/json”
這樣設定可以成功調用。
這樣就不成功了,web api 支援json string,不支援json 對象,因此只允許在body中有一個參數。
Type converters
可以使用類型轉換的方法,將請求的資料按字串處理,處理過程如下:
namespace WebAPITest { using System; using System.ComponentModel; using System.Globalization; public class TestTypeConverter: TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { returntrue; } returnbase.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { TestData data; if (TestData.TryParse((string) value, out data)) { return data; } } return base.ConvertFrom(context, culture, value); } } }
View Code
namespaceWebAPITest { using System.ComponentModel; [TypeConverter(typeof(TestTypeConverter))] public class TestData { public string Name { get; set; } public int Id { get; set; } public static bool TryParse(string s, outTestData result) { result = null; var parts = s.Split(‘,‘); if (parts.Length != 2) { return false; } int id; string name = parts[1]; if (int.TryParse(parts[0], out id)) { result = newTestData() { Id = id, Name = name }; return true; } return false; } } }
View Code
這樣就可以不用寫from url這樣調用: http://localhost:24367/api/Employee?data=10,jignesh%20trivedi
public HttpResponseMessage Get(TestData data) { …… return Request.CreateResponse(HttpStatusCode.OK, true); }
View Code
Model Binder
另外一種處理參數的方法,實現IModelBinder 介面,只用實現一個方法BindModel,下面的代碼從路由中讀取raw data,將其轉換成TestData,執行個體是一個簡單類型轉換,當然Model binder不限於簡單類型:
namespace WebAPITest { using System; using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using System.Web.Http.ValueProviders; public class CustomModelBinder: IModelBinder { static CustomModelBinder() { } public bool BindModel(HttpActionContextactionContext, ModelBindingContextbindingContext) { if (bindingContext.ModelType != typeof(TestData)) { return false; } ValueProviderResult val = bindingContext.ValueProvider.GetValue( bindingContext.ModelName); if (val == null) { return false; } string key = val.RawValue as string; if (key == null) { bindingContext.ModelState.AddModelError( bindingContext.ModelName, "Wrong value type"); returnfalse; } TestData result = newTestData(); var data = key.Split(newchar[] { ‘,‘ }); if (data.Length > 1) { result.Id = Convert.ToInt32(data[0]); result.Name = data[1]; bindingContext.Model = result; return true; } bindingContext.ModelState.AddModelError( bindingContext.ModelName, "Cannot convert value to TestData"); return false; } } }
View Code
另外需要註冊這個binder,我們需要在configuration中產生一個 model-binder provider 。這裡使用內建的provider:SimpleModelBinderProvider
namespace WebAPITest { using System.Web.Http; using System.Web.Http.ModelBinding; using System.Web.Http.ModelBinding.Binders; public static class WebApiConfig { public static void Register(HttpConfigurationconfig) { var provider = newSimpleModelBinderProvider( typeof(TestData), newCustomModelBinder()); config.Services.Insert(typeof(ModelBinderProvider), 0, provider); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); } } }
View Code
調用這個url:URI: http://localhost:24367/api/Employee?data=10,jignesh%20trivedi,有多種方法使用這個Model binder。在參數上使用特性:
public HttpResponseMessage Get([ModelBinder(typeof(CustomModelBinder))] TestData data) { …… return Request.CreateResponse(HttpStatusCode.OK, true); }
View Code
另外可以在類上使用這個特性:
[ModelBinder(typeof(CustomModelBinder))] public class TestData { //...... }
View Code
完了。。。。。
asp.net web api參數