首页 > 代码库 > 对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请求进行过滤处理,转换成接收着需要的格式