Search code examples
c#asp.net-mvc-5blazorblazor-server-side

ASP.NET MVC add headers and redirect to an external url


I need to write an small ASP.NET MVC website which sole purpose is to capture headers sent from a legacy website, add these headers to a request and redirect to a Blazor server app (including headers).

How can I add headers to a request and redirect to an external URL in a controller action?

I've tried HttpClient, WebClient and HttpWebRequest but none support redirecting.

I also tried:

Response.Headers.Add("Test", "Test redirect");
Response.Redirect("https://mywebsite.com/", true);

The redirection works but the header is not added.


Solution

  • You cannot do that, because 302 redirect are handled by browser and it will not re-attach headers, refer to this answer.

    So you can try to create a new response which you need to manually manage all response details, including status codes, redirect URLs, and all custom headers.

    example:

    Response.StatusCode = 302;
    
    Response.Headers.Add("Location", "https://mywebsite.com/");
    
    Response.Headers.Add("Test", "Test redirect");
    Response.Headers.Add("AnotherHeader", "AnotherValue");
    ...