如何解决使用IHttpClientFactory设置默认请求标头
我正在开发一个ASP.NET Core MVC App,在该应用程序中,我想在用户到达某个页面时为每个请求设置一个授权标头。我试图从HttpClient类使用DefaultRequestHeaders.Authorization。 但是,它只是不设置标题。 这是我的代码:
启动
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
//Some more code
}
控制器
public class MyController: Controller
{
private readonly System.Net.Http.IHttpClientFactory _clientFactory;
public MyController(System.Net.Http.IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public IActionResult MethodWhichIWantToSetThetoken()
{
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme,"veryBigTokenHere");
string abc = Request.Headers["Authorization"]; //Yeah,it's null!
return View();
}
解决方法
代替
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme,"veryBigTokenHere");
使用
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer","veryBigTokenHere");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。