如何从C#控制器重定向到URL(带有自定义标头)

时间:2019-04-11 17:06:51

标签: c# .net jwt authorization request-headers

我需要将用户的浏览器从.net核心C#控制器操作重定向到新的URL,并添加带有JWT令牌的自定义请求标头。

这可能吗?最好的方法是什么?

其他站点建议使用Response.Redirect(“ http://www.whatever.com”)和Server.Transfer(“ http://www.whatever.com”)。前者重定向,但我无法使用标题。后者我根本无法工作。服务器需要System.Web.HttpContext,它已从.net核心中删除。

[HttpPost]     公共无效RedirectWithHeaders(字符串令牌)     {         varpayload = decodeJwtFromString(token);         var jwt = makeNewJwt(payload);

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

此控制器操作需要接受一个发布的字符串(该部分正常工作),然后重定向或以其他方式导航到具有添加的授权标头(由解剖的发布的字符串制成)的新页面。

1 个答案:

答案 0 :(得分:1)

在Startup.cs中添加IActionContextAccessor

 services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

将其注入您的控制器并创建新的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; 
    }

}

使用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