asp.net webapi参数绑定

content={"content": [{"comb_id": "100323","comb_name": "双十一促销","netid": 0,"type": 0,"ischange":0,"goods": [{"skuid": "95526","amount": "3"},{"skuid": "94429","amount": "2"}]},{"comb_id": "100300","comb_name": "双十二促销","netid": 0,"type": 0,"ischange":0,"goods": [{"skuid": "95526","amount": "3"},{"skuid": "94429","amount": "2"}]}]}&notify_id=100&notify_time=2014-01-01 12:12:00&notify_type=InvSkuWm&sign=9MJfZcor07o5WP4F8W2qQA==

 

当有个post请求,body参数如上,这时我希望我的action能获取content参数并绑定到我action对应的参数实体上,可以通过重写ExecuteBindingAsync方法和GetBinding方法实现

 

/// <summary>
    /// 参数绑定
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CommonParameterBinding<T> : HttpParameterBinding
    {
        private readonly string _parameterName;
        public CommonParameterBinding(HttpParameterDescriptor descriptor,string parameterName) : base(descriptor)
        {
            _parameterName = parameterName;
        }

        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,
            CancellationToken cancellationToken)
        {
            var nv = actionContext.Request.Content.ReadAsFormDataAsync(cancellationToken).Result;
            var jsonStr = HttpUtility.UrlDecode(nv[_parameterName]);
            var instance = JsonHelper.ConvertToObject<T>(jsonStr);
            actionContext.ActionArguments[Descriptor.ParameterName] = instance;

            var tsc = new TaskCompletionSource<object>();
            tsc.SetResult(null);
            return tsc.Task;
        }
    }

  

public class CombinMappingBindingAttribute : ParameterBindingAttribute
    {
        public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
        {
            return parameter.ParameterType == typeof (CombMappingRequest)
                ? new CommonParameterBinding<CombMappingRequest>(parameter, "content")
                : parameter.BindAsError("Wrong parameter type");
        }
    }

  

/// <summary>
        /// 礼包对应关系
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult<NetResponse> Mapping([CombinMappingBinding]CombMappingRequest request)
        {
        }

  

测试了一下发现参数中只能有一个绑定。

posted @ 2016-11-22 20:09  itor  阅读(390)  评论(0编辑  收藏  举报