如何将HttpRequest转换为HttpRequestBase对象?


76

我的问题与此相反: 如何将HttpRequestBase转换为HttpRequest对象?

在我的ASP.NET MVC应用程序中,我有一种方法被许多接收HttpRequestBase作为参数的控制器使用。

现在,我必须从另一个方法(不是动作(它是nhibernate拦截器))中调用该方法。在第二种方法中,我可以访问HttpContext.Current.Request,即HttpRequest,并且无法将其强制转换为HttpRequestBase(由于命名原因,我认为它是可能的)。

有人知道这门课有什么关系吗,我该如何解决我的问题?谢谢。

Answers:



22

这是另一种不需要创建新实例的解决方案:

var httpRequestBase = myHttpRequest.RequestContext.HttpContext.Request;

1

在我的应用程序中,我有来自不同地方的调用,这些调用需要访问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答案,这些答案帮助我构建了这些扩展:


0

我发现以下扩展方法很有用:

    public static HttpContextBase AsBase(this HttpContext context)
    {
        return new HttpContextWrapper(context);
    }

    public static HttpRequestBase AsBase(this HttpRequest context)
    {
        return new HttpRequestWrapper(context);
    }

用法:

HttpContext.Current.AsBase()
HttpContext.Current.Request.AsBase()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.