在我的 ASP.NET MVC 控制器中,我有一个需要 HttpRequest 目的。我所能访问的只是 HttpRequestBase 目的。

无论如何我可以以某种方式转换它吗?

我可以/应该做什么?

有帮助吗?

解决方案

这是你的方法,这样你就可以重新写它采取HttpRequestBase?如果没有,你可以随时从HttpRequest获得当前HttpContext.Current.HttpRequest转嫁。不过,我经常包访问的HttpContext类里面像提到ASP.NET:。卸下的System.Web依赖获得更好的单元测试支持

其他提示

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

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

var httpRequestBase = new HttpRequestWrapper(Context.Request);

您可以只用

System.Web.HttpContext.Current.Request

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

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

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

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

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

this.HttpContext.ApplicationInstance.Context.Request

通常当您需要访问 HttpContext 控制器操作中的属性,您可以在设计方面做得更好。

例如,如果您需要访问当前用户,请为您的操作方法提供一个类型的参数 IPrincipal, ,您用一个填充 Attribute 并在测试时随心所欲地进行模拟。有关如何操作的小示例,请参阅 这篇博文, ,特别是第 7 点。

有没有办法这些类型之间进行转换。

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

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

这是一个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();
            }
        }
    }
}

它的工作像凯文说。

我使用一个静态方法来检索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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top