你的位置:首页 > 软件开发 > ASP.net > ASP.NET Web API中的参数绑定总结

ASP.NET Web API中的参数绑定总结

发布时间:2016-02-28 01:00:10
ASP.NET Web API中的action参数类型可以分为简单类型和复杂类型。HttpResponseMessage Put(int id, Product item)id是int类型,是简单类型,item是Product类型,是复杂类型。简单类型实参值从哪里读取呢?--一般 ...

 

get='_blank'>ASP.NET Web API中的action参数类型可以分为简单类型和复杂类型。HttpResponseMessage Put(int id, Product item)id是int类型,是简单类型,item是Product类型,是复杂类型。简单类型实参值从哪里读取呢?所谓的简单类型包括哪些呢?复杂类型实参值从哪里读取呢?复杂类型实参值是否可以从URI中获取呢?→ 有这样的一个类

public class Shape{  public double Width{get;set;}  public double Length{get;set;}}
public HttpResponseMessage Get([FromUri] Shape shape)→ 客户端就可以放在查询字符串中传...api/products/?Width=88&Length=199简单类型可以从请求的body中获取吗?→ action方法public HttpResponseMessage Post([FromBody] string name){...}→ 前端请求中Content-Type:applicaiton/json"hello world"API服务端会根据Content-Type的值选择合适的媒体类型。复杂类型是否可以从uri中的字符串获取呢?api/products/?shape=188,80如何把uri中查询字符串中shape的字段值,即以逗号分割的字符串转换成Shape类实例呢?public HttpResponseMessage Get(Shape shape)→ 客户端api/products/?shape=188,80是否可以通过Model Binder来实现自定义参数绑定过程呢?→ 自定义一个Model Binder

 

public class ShapeModelBinder : IModelBinder{  private static ConcurrentDictionary<string, Shape> _shapes = new ConcurrentDictionary<string, Shape>(StringComparer.OrdinalIgnoreCase);    static ShapeModelBinder()  {    _shapes["shape1"] = new Shape(){Width= 10, Length = 20};    _shapes["shape2"] = new Shape(){Width=12, Length = 22 };  }    public bool BindModel(HttpActionContext actionContext, ModelBindingContect biningContext)  {    if(bindingContext.ModelType != typeof(Shape))    {      return false;    }    ValueProviderResult val = bindingContext.ValueProvider.GetValue(bidingContext.ModelName);    if(val == null)    {      return false;    }        string key = val.RawValue as string;    if(key == null){      bdingContext.ModelState.AddModelError(bindingContext.ModelName, "值类型错误");      return false;    }        Shape shape;    if(_shapes.TryGetValue(key, out shape) || Shape.TryParse(key, shape))    {      bindingContext.Model = result;      return true;    }        bindingContext.ModelState.AddModelError(bindingContext.ModelName, "无法把字符串转换成Shape");    return false;  }}
→ 使用自定义的Model Binder可以运用在action中:public HttpResposneMessage Get([ModelBinder(typeof(ShapeModelBinder))] Shape shape);可以放在模型上:

[ModelBinder(typeof(Shape))]public class Shape{}
public HttpResponseMessage Get([ModelBinder] Shape shape);是否可以通过Value Provider来自定义参数绑定过程呢?比如,从前端cookie中获取值,自定义一个Value Provider.

 

public class MyCookieValueProvider : IValueProvider{  private Dictionary<string, string> _values;    public MyCookieValueProvider(HttpActionContext actionContext)  {    if(actionContext == null)    {      throw new ArgumentNullException("actionContext");    }        _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);    foreach(var cookie in actionContext.Request.Headers.GetCookies())    {      foreach(CookieState state in cookie.Cookies)      {        _values[state.Name] = state.Value;      }    }  }    public bool COntainsPrefix(string prefix)  {    return _values.keys.Contains(prefix);  }    public ValueProviderResult GetValue(string key)  {    string value;    if(_values.TryGetValue(key, out value))    {      return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);    }    return null;  }}
public HttpResponseMessage Get([ValueProvider(typeof(MyCookieValueProviderFactory))] Shape shape);

是否可以通过HttpParameterBinding实现参数绑定自定义呢?ModelBinderAttribute继承于ParameterBindingAttribute.

public abstract class ParameterBindingAttribute : Attribute{  public abstract HttpParameterBinding GetBinding(HttpParameterDescriptor parameter);}
假设,需要从前端请求的if-match和if-none-match字段获取ETag值。

 

public class ETag{  public string Tag{get;set;}}
如何使用自定义的HttpParameterBinding呢?public HttpResponseMessage Get([IfNoneMatch] ETag etag)还需要在全局注册:

config.ParameterBindingRules.Add(p => {  if(p.ParameterType == typeof(ETag) && p.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get))  {    return new ETagParameterBinding(p, ETagMatch.IfNoneMatch);  }  else  {    return null;  }})

原标题:ASP.NET Web API中的参数绑定总结

关键词:ASP.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。