我需要将用户的浏览器从.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
}
此控制器操作需要接受一个发布的字符串(该部分工作正常),然后重定向或以其他方式导航到具有添加的授权标头(由剖析的发布的字符串制成)的新页面。
在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("google.com",true);
result.UrlHelper = new UrlHelper(_accessor.ActionContext);
// Add the custom header
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