35197

C# - HttpWebResponse redirect to external URL

Question:

I'm trying to achieve the following:

<ul><li>I'm building an MVC website that will help me to automatically logon to another site.</li> <li><strong>WebsiteA</strong> will call <strong>WebsiteB</strong> using HttpWebRequest.</li> <li><strong>WebsiteA</strong> will send the details of the user through headers (request.headers.add)</li> <li><strong>WebsiteB</strong> will handle all the user authentication and internally it will redirect to another page granting access to that user.</li> </ul>

I've managed to achieve part of it but I'm stuck in displaying the redirection return. Anyone knows if this can be achieved?

Here is some code that gets called in the WebsiteA app:

[HttpPost] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] public ActionResult LogIn(myModel model) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://websiteB/LogIn.aspx"); request.AllowAutoRedirect = true; request.Method = "POST"; request.Headers.Add("MyUserToLogon", model.User); //I'm sending my user through headers string postData = "This is a test"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //Get the response from the Login Page HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); reader.Close(); dataStream.Close(); response.Close(); //What to do here? I want to go to the redirected page from WebSiteB/Page1.aspx //See code below for WebSiteB. return null; }

In WebSiteB I have the code that does the redirection when the user is successfully logged in:

....... users = Request.QueryString["MyUserToLogon"]; ....... private void LogIn(string user) { GrantUser(user, Session.SessionID); HttpCookie mycookie = new HttpCookie("test"); mycookie .Expires = DateTime.Now.AddMinutes(10); Response.Cookies.Add(mycookie); Response.AddHeader("mycookie ", mycookie .Value); Response.Redirect("WebsiteB/Page1.aspx"); }

Any help would be really appreciated.

Answer1:

I had the same problem for my sites.

You can't use redirect because it is done by IIS and you will never receive all your authentication cookies back from WebSiteB.

In my case returning view instead of redirect worked. And then you redirect on WebSiteA after setting cookies

Also seems you need to add cookie container for your request to get cookies back.

Here is may code

Landing site

[HttpPost] public ActionResult Login(string accountId) { var url = "http://...." var request = (HttpWebRequest)WebRequest.Create(url + "/Account/WamLogin/"); request.Headers.Add("user", accountId); request.CookieContainer = new CookieContainer(); var response = (HttpWebResponse)request.GetResponse(); foreach (Cookie cook in response.Cookies) { Response.Cookies.Add(new HttpCookie(cook.Name, cook.Value) { Expires = cook.Expires, HttpOnly = cook.HttpOnly, Domain = cook.Domain }); } return new RedirectResult(url); }

Here is WebSiteB code

[AllowAnonymous] public virtual ActionResult WamLogin(string returnUrl, string id) { var accountId= Request.Headers["user"]; ..... return View(MVC.Account.Views.Login); }

Hope this will help you

Recommend

  • how to display image directly from httpwebresponse stream in asp.net?
  • How to get redirected url as string after request
  • powershell curl and WebRequest both follow redirects
  • Removing a particular header item in HTTP web requests
  • How to prevent namespace wrapper tags in SOAP wsdl?
  • NUnit Multiple TestFixture with different Category attribute
  • Dynamically create button using Tkinter
  • Unexpected end of JSON input Angular 2(4) http get request
  • Wait for subscription to complete
  • Nginx raises 404 when using format => 'js'
  • How to Cache Images Dynamically-Generated with PHP?
  • PHP - sending email with attachment does not show message content
  • Streamed transfer restrictions with WCF
  • HttpRequestMessage Content Disposition null when unit testing
  • missing pie chart and other elements when display serenity report from jenkins
  • angular2 http.post() to local json file
  • Uber API - requests endpoint cannot read read json
  • XNU incudes in Kext
  • Regex for URL rewrite with optional query string parameters
  • What is corresponding c++ data type to SQL numeric(18,0) data type?
  • Other than Linq to SQL does anything else consume INotifyPropertyChanging?
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Switch to popup in python using selenium
  • Content-Length header not returned from Pylons response
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • AngularJs get employee from factory
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Memory offsets in inline assembly
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • Turn off referential integrity in Derby? is it possible?
  • Can't mass-assign protected attributes when import data from csv file
  • JaxB to read class hierarchy
  • Programmatically clearing map cache
  • UserPrincipal.Current returns apppool on IIS
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize