문제

내 ASP.NET MVC 컨트롤러 내부에는 필요한 메소드가 있습니다. HttpRequest 물체. 내가 접근 할 수있는 것은 HttpRequestBase 물체.

어쨌든 나는 이것을 어떻게 든 이것을 변환 할 수 있습니까?

무엇을 할 수 있습니까?

도움이 되었습니까?

해결책

그것은 당신의 방법입니까, 당신은 그것을 다시 작성할 수 있습니다. HttpRequestBase? 그렇지 않다면 언제든지 전류를 얻을 수 있습니다 HttpRequest ~에서 HttpContext.Current.HttpRequest 에 전달하는. 그러나 나는 종종 언급 된 것처럼 클래스 내에서 HTTPContext에 대한 액세스를 랩핑합니다. ASP.NET : System.Web 종속성 제거 더 나은 단위 테스트 지원을 위해.

다른 팁

테스트가 불가능한 콘크리트 버전 (타입 콕이나 다른 마법없이)과 달리 애플리케이션에서 항상 httprequestbase 및 httpresponsebase를 사용해야합니다.

간단히 사용하십시오 httprequestwrapper 아래 그림과 같이 수업을 변환합니다.

var httpRequestBase = new HttpRequestWrapper(Context.Request);

당신은 그냥 사용할 수 있습니다

System.Web.HttpContext.Current.Request

여기서 핵심은 "올바른"httpcontext에 도달하려면 풀 네임 스페이스가 필요하다는 것입니다.

나는이 질문이 요청 된 지 4 년이 지났다는 것을 알고 있지만, 이것이 누군가를 도울 것이라면 여기에서 당신은 간다!

(편집 : Kevin Hakanson이 이미이 답변을 주었다는 것을 알았습니다.

httprequestbase를 사용하여 httprequestwrapper를 사용/작성하십시오.

asp.net mvc4 .net 4.5에서 httprequest를 얻으려면 다음을 수행 할 수 있습니다.

this.HttpContext.ApplicationInstance.Context.Request

일반적으로 액세스해야 할 때 HttpContext 컨트롤러 동작의 속성, 더 나은 디자인을 현명하게 할 수있는 일이 있습니다.

예를 들어, 현재 사용자에게 액세스 해야하는 경우 액션 메소드를 유형의 매개 변수에게 제공하십시오. IPrincipal, 당신이 an Attribute 테스트 할 때 원하는대로 조롱합니다. 방법에 대한 작은 예는 참조하십시오 이 블로그 게시물, 구체적으로 지점 7.

이러한 유형간에 변환 할 방법은 없습니다.

우리는 비슷한 경우가있었습니다. 우리는 클래스/웹 서비스 메소드를 다시 작성하여 "기본"접미사가없는 닫기 이름 유형 대신 httpcontextbase, httpepplicationstatebase, httpserveritilitybase, httpsessionstatebase ... 그들은 집에서 만든 조롱으로 다루기가 훨씬 쉽습니다.

할 수 없어서 미안하다고 생각합니다.

이것은 요청을 수락하고 인바운드 httprequestbase mvc 객체를 System.web.httpwebrequest로 변환하는 ASP.NET MVC 3.0 AsyncController입니다. 그런 다음 요청을 비동기로 보냅니다. 응답이 다시 오면 System.web.httpwebresponse를 MVC 컨트롤러를 통해 반환 할 수있는 MVC HTTPRESPONSEBASE 객체로 다시 변환합니다.

이 질문에 명시 적으로 대답하기 위해 BuildWebRequest () 함수에만 관심이 있다고 생각합니다. 그러나 전체 파이프 라인을 통해 Baserequest> 요청에서 변환 한 다음 응답> BaseResponse를 통해 이동하는 방법을 보여줍니다. 두 가지 공유가 유용 할 것이라고 생각했습니다.

이 클래스를 통해 웹 프록시 역할을하는 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, 그리고 항상 a 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