首页 > 代码库 > 对http请求进行过滤处理,转换成接收着需要的格式
对http请求进行过滤处理,转换成接收着需要的格式
需要在Global.asax的Application中进行初始化处理 这样:GlobalConfiguration.Configuration.MessageHandlers.Add(new DefaultHandler())
然后在App_Start文件夹中添加 DefaultHandler 类复制下面的代码
public class DefaultHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.RequestUri = new Uri(request.RequestUri.ToString()); MediaTypeHeaderValue contentType = request.Content.Headers.ContentType; if (contentType != null) { switch (contentType.MediaType) { case "application/x-www-form-urlencoded": { NameValueCollection formData = await request.Content.ReadAsFormDataAsync(cancellationToken); request.Content = new FormUrlEncodedContent(Correct(formData)); //如下代码为了预下订单使用 var formDataDic = formData.ToDictionary(); var str = ConvertToJsonString(formDataDic); HttpContext.Current.Request.Headers.Add("formDataToJson", str); } break; case "multipart/form-data": { NameValueCollection formData = await request.Content.ReadAsFormDataAsync(cancellationToken); request.Content = new FormUrlEncodedContent(Correct(formData)); } break; case "application/json": { HttpContentHeaders oldHeaders = request.Content.Headers; string formData = http://www.mamicode.com/await request.Content.ReadAsStringAsync(); request.Content = new StringContent(formData); ReplaceHeaders(request.Content.Headers, oldHeaders); } break; default: throw new Exception("Implement It!"); } } return await base.SendAsync(request, cancellationToken); } private static IEnumerable<KeyValuePair<string, string>> Correct(NameValueCollection formData) { return formData.Keys.Cast<string>().Select(key => new KeyValuePair<string, string>(key, formData[key])).ToList(); } private static void ReplaceHeaders(HttpHeaders currentHeaders, HttpHeaders oldHeaders) { currentHeaders.Clear(); foreach (var item in oldHeaders) currentHeaders.Add(item.Key, item.Value); } private string ConvertToJsonString(IDictionary<string, string> param) { dynamic myObj = new ExpandoObject(); var dic = (IDictionary<string, object>)myObj; foreach (var item in param) { if (item.Value.StartsWith("[") || item.Value.StartsWith("{")) { dic[item.Key] = JsonConvert.DeserializeObject(item.Value); } else { dic[item.Key] = item.Value; } } return JsonConvert.SerializeObject(myObj); } } public static class NVCExtender { public static IDictionary<string, string> ToDictionary(this NameValueCollection source) { return source.AllKeys.ToDictionary(k => k, k => source[k]); } }
对http请求进行过滤处理,转换成接收着需要的格式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。