Search code examples
c#asp.net-mvcasp.net-mvc-3asp.net-mvc-4httphandler

Asp.net mvc httpthandler redirection to inner server


I want to create an http handler that sends request to url that comes with querystring parameter. Because the url parameter is backend server. Users can not access it so I want to send request with a proxy script.

http://frontendserver?url=http://backendserver?x=1&y=2

  public class GeolocateRequestHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            TransferUserIfAuthenticated(new HttpContextWrapper(context));
        }

        private static void TransferUserIfAuthenticated(HttpContextBase context)
        {
            if (context.User.Identity.IsAuthenticated)
            {
                var url = context.Request.QueryString["url"];
                ??? redirect to url (locale lan server)
            }
        }
    }

Should I do via a .Net WenClient object or is there a short way else?


Solution

  • WebClient is used to create a new Request and get Response.

    You can make redirection in current context using it's Response object.

    context.Response.Redirect(url)
    

    EDIT

    I can't give you exact working code, by I'll explain in theory.

    Perform a request with HttpWebRequest. Get response and rewrite data into context.Response.

    You have to rewrite content, headers(like content-type), cookies if needed.

    var http = (HttpWebRequest)WebRequest.Create("http://example.com");
    var response = (HttpWebResponse)http.GetResponse();