using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; namespace WcfControlMonitorWebLib { /// /// HTTP 请求的扩展方法 /// internal static class RequestExtension { /// /// 获取令牌,即服务端对应的 Session id /// internal static string Token(this HttpRequestMessage request) { if (request.Headers.Contains("token")) { return request.Headers.GetValues("token").First(); } else { return null; } } /// /// 以动态类型解析请求数据 /// internal static dynamic Data(this HttpRequestMessage request) { return request.Data(); } /// /// 解析请求数据,并尝试转换为指定类型 /// internal static T Data(this HttpRequestMessage request) { var obj = new JObject(); foreach (KeyValuePair item in request.GetRouteData()?.Values) { obj.Add(item.Key, new JValue(item.Value)); } foreach (KeyValuePair item in request.GetQueryNameValuePairs()) { obj.Add(item.Key, item.Value); } var task = request.Content.ReadAsAsync(); task.Wait(); if (task.Result != null) { foreach (var item in task.Result) { obj.Add(item); } } return obj.ToObject(); } } }