web-dev-qa-db-ja.com

HttpRequestBaseをHttpRequestオブジェクトに変換するにはどうすればよいですか?

aSP.NET MVCコントローラー内には、HttpRequestオブジェクトを必要とするメソッドがあります。私がアクセスできるのはHttpRequestBaseオブジェクトだけです。

とにかくこれを何らかの方法で変換できますか?

何ができますか?

82
Pure.Krome

それはあなたの方法ですので、HttpRequestBaseを取るように書き直すことができますか?そうでない場合は、常にHttpContext.Current.HttpRequestから現在のHttpRequestを取得して渡すことができます。ただし、ユニットテストのサポートを改善するために、 ASP.NET:System.Web Dependenciesの削除 に記載されているように、クラス内でHttpContextへのアクセスをラップすることがよくあります。

48
Kevin Hakanson

テストすることが不可能な具体的なバージョン(typemockまたはその他の魔法なし)ではなく、常にアプリケーションでHttpRequestBaseとHttpResponseBaseを使用する必要があります。

HttpRequestWrapper クラスを使用して、次のように変換します。

var httpRequestBase = new HttpRequestWrapper(Context.Request);
65
CountZero

あなただけを使用することができます

System.Web.HttpContext.Current.Request

ここで重要なのは、「正しい」HttpContextを取得するには完全な名前空間が必要なことです。

この質問が出されてから4年が経ちましたが、これが誰かを助けるなら、ここに行きます!

編集

29
adamgede

HttpRequestBaseを使用してHttpRequestWrapperを使用または作成してみてください。

9
Klaas

ASP.NET MVC4 .NET 4.5でHttpRequestを取得するには、次の操作を実行できます。

this.HttpContext.ApplicationInstance.Context.Request
8
Mohamed Mansour

通常、コントローラーアクションでHttpContextプロパティにアクセスする必要がある場合、賢明に設計できることがあります。

たとえば、現在のユーザーにアクセスする必要がある場合は、アクションメソッドにIPrincipal型のパラメーターを指定します。このパラメーターには、テスト時にAttributeとモックを入れます。方法の簡単な例については、 このブログ投稿 、特にポイント7を参照してください。

4
Tomas Aschan

これは、要求を受け入れ、インバウンドHttpRequestBase MVCオブジェクトをSystem.Web.HttpWebRequestに変換するASP.Net MVC 3.0 AsyncControllerです。次に、リクエストを非同期に送信します。応答が返されると、System.Web.HttpWebResponseをMVCコントローラー経由で返されるMVC HttpResponseBaseオブジェクトに変換します。

この質問に明示的に答えるために、BuildWebRequest()関数にのみ興味があると思います。ただし、パイプライン全体を移動する方法を示しています-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();
            }
        }
    }
}
2
Kenn

これらのタイプを変換する方法はありません。

同様のケースがありました。クラス/ Webサービスメソッドを書き直して、「Base」サフィックスのない近い名前のタイプ(HttpContext、... HttpSessionState)の代わりに、HttpContextBase、HttpApplicationStateBase、HttpServerUtilityBase、HttpSessionStateBase ...を使用するようにしました。自家製のモックを使用すると、処理がはるかに簡単になります。

できなかったのが残念です。

2
Barbara Post

ケビンが言ったように機能した。

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)
1
RogerGales