在我的应用程序中,我有来自不同地方的调用,这些调用需要访问HttpRequestBase。我创建了这套扩展方法,以获取几种不同的Http类型并将其从HttpRequestBase转换为HttpRequestBase,然后在需要访问请求时,将HttpRequestBase用作应用程序中接口和类方法的基本类型。
public static class RequestExtensions
{
public static HttpRequestBase GetHttpRequestBase(this HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentException("Context is null.");
}
return httpContext.Request.ToHttpRequestBase();
}
public static HttpRequestBase GetHttpRequestBase(this HttpRequestMessage httpRequestMessage)
{
if (httpRequestMessage == null)
{
throw new ArgumentException("Request message is null.");
}
HttpContextWrapper context = null;
if (httpRequestMessage.Properties.ContainsKey("MS_HttpContext"))
{
context = httpRequestMessage.Properties["MS_HttpContext"] as HttpContextWrapper;
}
if (context == null)
{
throw new ArgumentException("Context is null.");
}
return context.Request;
}
public static HttpRequestBase GetHttpRequestBase(this HttpApplication httpApplication)
{
if (httpApplication == null)
{
throw new ArgumentException("Application is null.");
}
return httpApplication.Request.ToHttpRequestBase();
}
public static HttpRequestBase ToHttpRequestBase(this HttpRequest httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentException("Request is null.");
}
return new HttpRequestWrapper(httpRequest);
}
}
我遇到了几个SO答案,这些答案帮助我构建了这些扩展:
new HttpRequestWrapper(HttpContext.Current.Request)