asp.net web api參數

來源:互聯網
上載者:User

標籤:

翻譯自: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參數

相關文章

聯繫我們

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