Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to URL (with custom headers) from C# Controller

I need to redirect the user's browser to a new URL from my .NET Core C# controller action, and add my own custom request header with a JWT token.

Is this possible? What's the best way to do this?

Other sites have suggested Response.Redirect("http://www.whatever.com") and Server.Transfer("http://www.whatever.com"). The former redirects, but I can't get the headers to work. The latter I couldn't get to work at all. Server requires System.Web.HttpContext, which has been removed from .NET Core.

[HttpPost]
public void RedirectWithHeaders(string token)
{
    var payload = decodeJwtFromString(token);
    var jwt = makeNewJwt(payload);

    // Now go to the URL with an authorization header
}

This controller action needs to accept a posted string (that part's working fine) and then redirect or otherwise navigate to a new page with an added authorization header (made out of the dissected posted string).

like image 710
Alex Avatar asked Sep 06 '25 03:09

Alex


1 Answers

Add IActionContextAccessor in your Startup.cs

 services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

Inject it in your controller and Create new RedirectResult :

public class HomeController : Controller
   {
    private readonly ILogger<HomeController> _logger;
    private readonly IActionContextAccessor _accessor;

    public HomeController(ILogger<HomeController> logger, IActionContextAccessor accessor)
    {
        _logger = logger;
        _accessor = accessor;
    }

    public IActionResult RedirectTo()
    {
        // Create RedirectResult and add URLHelper 
        var result = new RedirectResult("www.google.com",true);
        result.UrlHelper = new UrlHelper(_accessor.ActionContext); 

        result.UrlHelper
              .ActionContext
              .HttpContext
              .Response.Redirect("www.google.com");

         result.UrlHelper
               .ActionContext
               .HttpContext
               .Response.Headers.Add("Just-Token", new StringValues("JustToken"));
        return result; 
    }

}

Response using curl -i cmd :

curl -i localhost:5000/Home/redirectTo
    HTTP/1.1 301 Moved Permanently
    Date: Thu, 02 Apr 2020 13:09:52 GMT
    Server: Kestrel
    Content-Length: 0
    Location: google.com
    Just-Token: JustToken
like image 61
tlejmi Avatar answered Sep 07 '25 22:09

tlejmi