How do I convert an HttpRequest into an HttpRequestBase object?

后端 未结 4 1383
耶瑟儿~
耶瑟儿~ 2021-02-01 12:09

My problem is the opposite of this: How do I convert an HttpRequestBase into an HttpRequest object?

In my ASP.NET MVC application I have a method used by many controlle

4条回答
  •  再見小時候
    2021-02-01 12:26

    In my application I had calls coming from several different places that needed access to the HttpRequestBase. I created this set of extension methods to get and convert from several different Http types into a HttpRequestBase, then used HttpRequestBase as the base type for interface and class methods through the application when I needed access to the request.

    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);
        }
    }
    

    I came across several SO answers that helped me build these extensions:

    • How do I convert an HttpRequestBase into an HttpRequest object?
    • Convert HttpRequestMessage to HttpRequest
    • Get the IP address of the remote host

提交回复
热议问题