标签:
在使用第三方接口时,有时候会看到
public class FromUriOrBodyParameterBinding : HttpParameterBinding { HttpParameterBinding _defaultUriBinding; HttpParameterBinding _defaultFormatterBinding; public FromUriOrBodyParameterBinding(HttpParameterDescriptor desc) : base(desc) { _defaultUriBinding = new FromUriAttribute().GetBinding(desc); _defaultFormatterBinding = new FromBodyAttribute().GetBinding(desc); } public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Content != null && actionContext.Request.Content.Headers.ContentLength > 0) { // we have something from the body, try that first return _defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); } else { // we need to read things from uri return _defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); } }
config.ParameterBindingRules.Insert(0, x => { if (x.ParameterType == typeof(LoginModel)) { return new FromUriOrBodyParameterBinding(x); } return null; });
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] public sealed class FromUriOrBodyAttribute : ParameterBindingAttribute { public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter) { return new FromUriOrBodyParameterBinding(parameter); } public class FromUriOrBodyParameterBinding : HttpParameterBinding { HttpParameterBinding _defaultUriBinding; HttpParameterBinding _defaultFormatterBinding; public FromUriOrBodyParameterBinding(HttpParameterDescriptor desc) : base(desc) { _defaultUriBinding = new FromUriAttribute().GetBinding(desc); _defaultFormatterBinding = new FromBodyAttribute().GetBinding(desc); } public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Content != null && actionContext.Request.Content.Headers.ContentLength > 0) { // we have something from the body, try that first return _defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); } else { // we need to read things from uri return _defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); } } } }
[AcceptVerbs("GET","POST")] public IHttpActionResult Login([FromUriOrBody]LoginModel login) { return Ok(login); }
让asp.net web api同时支持[AcceptVerbs("GET","POST")]
标签:
原文地址:http://www.cnblogs.com/chwenj/p/4914588.html