如何将HttpRequestBase转换为HttpRequest对象?

在我的ASP.NET MVC控制器里面,我有一个需要HttpRequest对象的方法。 我有权访问的是一个HttpRequestBase对象。

无论如何,我可以以某种方式转换这个?

我能做什么/我该怎么做?

这是你的方法,所以你可以重新写它来采取HttpRequestBase ? 如果没有,你可以总是从HttpContext.Current.HttpRequest获得当前的HttpRequest 。 但是,我经常在类中提到访问HttpContext的方法,就像ASP.NET中提到的:删除System.Web Dependencies以获得更好的unit testing支持。

你应该总是在你的应用程序中使用HttpRequestBase和HttpResponseBase作为与不可能testing的具体版本(没有typemock或其他一些魔术)。

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

 var httpRequestBase = new HttpRequestWrapper(Context.Request); 

你可以使用

 System.Web.HttpContext.Current.Request 

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

我知道这个问题已经过了四年了,但如果这能帮助某人,那么你就去!

(编辑:我看到凯文Hakanson已经给出了这个答案…所以希望我的回应将帮助那些只是阅读答案,而不是评论的人)。

尝试使用/创build一个HttpRequestWrapper使用您的HttpRequestBase。

要在ASP.NET MVC4 .NET 4.5中获得HttpRequest,可以执行以下操作:

 this.HttpContext.ApplicationInstance.Context.Request 

通常,当您需要访问控制器操作中的HttpContext属性时,您可以更好地进行devise。

例如,如果您需要访问当前用户,请为您的操作方法提供一个types为IPrincipal的参数,您可以根据需要在testing时填充Attribute和模拟。 有关如何的一个小例子,请参阅此博客文章 ,并特别指出7。

这些types之间没有办法转换。

我们有类似的情况。 我们重写了我们的类/ Web服务方法,以便它们使用HttpContextBase,HttpApplicationStateBase,HttpServerUtilityBase,HttpSessionStateBase …而不是没有“Base”后缀(HttpContext,… HttpSessionState)的closures名称的types。 用自制的嘲讽处理起来要容易得多。

我感到抱歉,你不能这样做。

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

为了明确回答这个问题,我想你只会对BuildWebRequest()函数感兴趣。 但是,它演示了如何遍历整个pipe道 – 从BaseRequest> Request和Response> 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(); } } } } 

它像凯文说的那样工作。

我正在使用静态方法来检索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)