如何转换的HttpRequestBase成一个HttpRequest对象?(How do I con

2019-07-18 17:37发布

我的ASP.NET MVC控制器里面,我已经得到了需要的方法HttpRequest对象。 所有我曾访问是HttpRequestBase对象。

反正我有可以以某种方式转换呢?

有什么可以/我应该怎么办?

Answer 1:

它是你的方法,这样你就可以重新写它采取HttpRequestBase ? 如果没有,你总是可以得到当前HttpRequestHttpContext.Current.HttpRequest转嫁。 不过,我经常换像提到一个类的内部访问HttpContext的ASP.NET:删除的System.Web依赖更好的单元测试支持。



Answer 2:

你应该总是使用HttpRequestBase和HttpResponseBase在你的应用程序,而不是对具体的版本是不可能的测试(不typemock或其他一些魔法)。

只需使用HttpRequestWrapper类,如下图所示转换。

var httpRequestBase = new HttpRequestWrapper(Context.Request);


Answer 3:

你可以只用

System.Web.HttpContext.Current.Request

这里的关键是,你需要完整的命名空间去“正确”的HttpContext。

我知道这是连续4年以来,这一问题被问过,但如果这将帮助别人,那么在这里你去!

(编辑:我看到凯文Hakanson潜在已经给了这个答案......所以希望我的回答可以帮助这些人谁刚才读的答案,而不是评论。):)



Answer 4:

尝试使用/使用HttpRequestBase创建HttpRequestWrapper。



Answer 5:

要获得的HttpRequest在ASP.NET MVC4 .NET 4.5,你可以做到以下几点:

this.HttpContext.ApplicationInstance.Context.Request


Answer 6:

通常,当您需要访问HttpContext在控制器的动作特性,有一些东西,你可以做明智的更好的设计。

例如,如果你需要访问当前用户,让您的操作方法类型参数IPrincipal ,你有填充Attribute ,你想测试时和模拟。 有关如何一个小例子,看这个博客帖子 ,并具体点7。



Answer 7:

有没有办法将这些类型之间的转换。

我们也有类似的情况。 我们改写了我们的类/ Web服务的方法,以便他们使用HttpContextBase,HttpApplicationStateBase,的HttpServerUtilityBase,HttpSessionStateBase ...而不是类型接近的名字没有“基地”后缀(HttpContext的,... HttpSessionState)。 他们是一个更容易处理与自制的嘲讽。

我感到遗憾,你不能这样做。



Answer 8:

这是一个ASP.Net MVC 3.0 AsyncController它接受请求,呼入HttpRequestBase MVC对象转换为System.Web.HttpWebRequest。 然后,它异步地发送请求。 当响应返回,它的System.Web.HttpWebResponse转换回其可以通过MVC控制器返回一个MVC HttpResponseBase对象。

要明确地回答这个问题,我想你只能将感兴趣的BuildWebRequest()函数。 然而,它演示了如何通过整个管道移动 - 从BaseRequest>请求转换,然后响应> BaseResponse。 我想分享两个将是有益的。

通过这些课程,你可以充当Web代理的MVC服务器。

希望这可以帮助!

控制器:

[HandleError]
public class MyProxy : AsyncController
{
    [HttpGet]
    public void RedirectAsync()
    {
        AsyncManager.OutstandingOperations.Increment();

        var hubBroker = new RequestBroker();
        hubBroker.BrokerCompleted += (sender, e) =>
        {
            this.AsyncManager.Parameters["brokered"] = e.Response;
            this.AsyncManager.OutstandingOperations.Decrement();
        };

        hubBroker.BrokerAsync(this.Request, redirectTo);
   }

    public ActionResult RedirectCompleted(HttpWebResponse brokered)
    {
        RequestBroker.BuildControllerResponse(this.Response, brokered);
        return new HttpStatusCodeResult(Response.StatusCode);
    }
}

这是代理类确实繁重:

namespace MyProxy
{
    /// <summary>
    /// Asynchronous operation to proxy or "broker" a request via MVC
    /// </summary>
    internal class RequestBroker
    {
        /*
         * HttpWebRequest is a little protective, and if we do a straight copy of header information we will get ArgumentException for a set of 'restricted' 
         * headers which either can't be set or need to be set on other interfaces. This is a complete list of restricted headers.
         */
        private static readonly string[] RestrictedHeaders = new string[] { "Accept", "Connection", "Content-Length", "Content-Type", "Date", "Expect", "Host", "If-Modified-Since", "Range", "Referer", "Transfer-Encoding", "User-Agent", "Proxy-Connection" };

        internal class BrokerEventArgs : EventArgs
        {
            public DateTime StartTime { get; set; }

            public HttpWebResponse Response { get; set; }
        }

        public delegate void BrokerEventHandler(object sender, BrokerEventArgs e);

        public event BrokerEventHandler BrokerCompleted;

        public void BrokerAsync(HttpRequestBase requestToBroker, string redirectToUrl)
        {
            var httpRequest = BuildWebRequest(requestToBroker, redirectToUrl);

            var brokerTask = new Task(() => this.DoBroker(httpRequest));
            brokerTask.Start();
        }

        private void DoBroker(HttpWebRequest requestToBroker)
        {
            var startTime = DateTime.UtcNow;

            HttpWebResponse response;
            try
            {
                response = requestToBroker.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                Trace.TraceError("Broker Fail: " + e.ToString());

                response = e.Response as HttpWebResponse;
            }

            var args = new BrokerEventArgs()
            {
                StartTime = startTime,
                Response = response,
            };

            this.BrokerCompleted(this, args);
        }

        public static void BuildControllerResponse(HttpResponseBase httpResponseBase, HttpWebResponse brokeredResponse)
        {
            if (brokeredResponse == null)
            {
                PerfCounters.ErrorCounter.Increment();

                throw new GriddleException("Failed to broker a response. Refer to logs for details.");
            }

            httpResponseBase.Charset = brokeredResponse.CharacterSet;
            httpResponseBase.ContentType = brokeredResponse.ContentType;

            foreach (Cookie cookie in brokeredResponse.Cookies)
            {
                httpResponseBase.Cookies.Add(CookieToHttpCookie(cookie));
            }

            foreach (var header in brokeredResponse.Headers.AllKeys
                .Where(k => !k.Equals("Transfer-Encoding", StringComparison.InvariantCultureIgnoreCase)))
            {
                httpResponseBase.Headers.Add(header, brokeredResponse.Headers[header]);
            }

            httpResponseBase.StatusCode = (int)brokeredResponse.StatusCode;
            httpResponseBase.StatusDescription = brokeredResponse.StatusDescription;

            BridgeAndCloseStreams(brokeredResponse.GetResponseStream(), httpResponseBase.OutputStream);
        }

        private static HttpWebRequest BuildWebRequest(HttpRequestBase requestToBroker, string redirectToUrl)
        {
            var httpRequest = (HttpWebRequest)WebRequest.Create(redirectToUrl);

            if (requestToBroker.Headers != null)
            {
                foreach (var header in requestToBroker.Headers.AllKeys)
                {
                    if (RestrictedHeaders.Any(h => header.Equals(h, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        continue;
                    }                   

                    httpRequest.Headers.Add(header, requestToBroker.Headers[header]);
                }
            }

            httpRequest.Accept = string.Join(",", requestToBroker.AcceptTypes);
            httpRequest.ContentType = requestToBroker.ContentType;
            httpRequest.Method = requestToBroker.HttpMethod;

            if (requestToBroker.UrlReferrer != null)
            {
                httpRequest.Referer = requestToBroker.UrlReferrer.AbsoluteUri;
            }

            httpRequest.UserAgent = requestToBroker.UserAgent;

            /* This is a performance change which I like.
             * If this is not explicitly set to null, the CLR will do a registry hit for each request to use the default proxy.
             */
            httpRequest.Proxy = null;

            if (requestToBroker.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
            {
                BridgeAndCloseStreams(requestToBroker.InputStream, httpRequest.GetRequestStream());
            }

            return httpRequest;
        }

        /// <summary>
        /// Convert System.Net.Cookie into System.Web.HttpCookie
        /// </summary>
        private static HttpCookie CookieToHttpCookie(Cookie cookie)
        {
            HttpCookie httpCookie = new HttpCookie(cookie.Name);

            foreach (string value in cookie.Value.Split('&'))
            {
                string[] val = value.Split('=');
                httpCookie.Values.Add(val[0], val[1]);
            }

            httpCookie.Domain = cookie.Domain;
            httpCookie.Expires = cookie.Expires;
            httpCookie.HttpOnly = cookie.HttpOnly;
            httpCookie.Path = cookie.Path;
            httpCookie.Secure = cookie.Secure;

            return httpCookie;
        }

        /// <summary>
        /// Reads from stream into the to stream
        /// </summary>
        private static void BridgeAndCloseStreams(Stream from, Stream to)
        {
            try
            {
                int read;
                do
                {
                    read = from.ReadByte();

                    if (read != -1)
                    {
                        to.WriteByte((byte)read);
                    }
                }
                while (read != -1);
            }
            finally 
            {
                from.Close();
                to.Close();
            }
        }
    }
}


Answer 9:

它的工作就像凯文说。

我使用一个静态方法来检索HttpContext.Current.Request ,所以始终有一个HttpRequest需要的时候使用的对象。

在这里,在助手类

public static HttpRequest GetRequest()
{
    return HttpContext.Current.Request;
}

在这里,在控制器

if (AcessoModel.UsuarioLogado(Helper.GetRequest()))

在这里查看

bool bUserLogado = ProjectNamespace.Models.AcessoModel.UsuarioLogado(
                      ProjectNamespace.Models.Helper.GetRequest()
                   );

if (bUserLogado == false) { Response.Redirect("/"); }

我的方法UsuarioLogado

public static bool UsuarioLogado(HttpRequest Request)


文章来源: How do I convert an HttpRequestBase into an HttpRequest object?