|
|
using System.Collections.Generic;
|
|
|
using System.Linq;
|
|
|
using System.Net.Http;
|
|
|
using System.Net.Http.Headers;
|
|
|
|
|
|
namespace System.Web.Http
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static class HttpRequestMessageExtensions
|
|
|
{
|
|
|
|
|
|
private const string HttpContext = "MS_HttpContext";
|
|
|
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static Dictionary<string, string> GetQueryStrings(this HttpRequestMessage request)
|
|
|
{
|
|
|
return request.GetQueryNameValuePairs()
|
|
|
.ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase);
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string GetQueryString(this HttpRequestMessage request, string key)
|
|
|
{
|
|
|
|
|
|
var queryStrings = request.GetQueryNameValuePairs();
|
|
|
if (queryStrings == null)
|
|
|
return null;
|
|
|
|
|
|
var match = queryStrings.FirstOrDefault(kv => string.Compare(kv.Key, key, true) == 0);
|
|
|
if (string.IsNullOrEmpty(match.Value))
|
|
|
return null;
|
|
|
|
|
|
return match.Value;
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string GetHeader(this HttpRequestMessage request, string key)
|
|
|
{
|
|
|
IEnumerable<string> keys = null;
|
|
|
if (!request.Headers.TryGetValues(key, out keys))
|
|
|
return null;
|
|
|
|
|
|
return keys.First();
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string GetCookie(this HttpRequestMessage request, string cookieName)
|
|
|
{
|
|
|
CookieHeaderValue cookie = request.Headers.GetCookies(cookieName).FirstOrDefault();
|
|
|
if (cookie != null)
|
|
|
return cookie[cookieName].Value;
|
|
|
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
|
|
|
public static string GetClientIpAddress(this HttpRequestMessage request)
|
|
|
{
|
|
|
if (request.Properties.ContainsKey(HttpContext))
|
|
|
{
|
|
|
dynamic ctx = request.Properties[HttpContext];
|
|
|
if (ctx != null)
|
|
|
{
|
|
|
return ctx.Request.UserHostAddress;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if (request.Properties.ContainsKey(RemoteEndpointMessage))
|
|
|
{
|
|
|
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
|
|
|
if (remoteEndpoint != null)
|
|
|
{
|
|
|
return remoteEndpoint.Address;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
}
|
|
|
} |