How do I set a cookie on HttpClient's HttpRequestMessage

后端 未结 5 1222
眼角桃花
眼角桃花 2020-11-22 09:57

I am trying to use the web api\'s HttpClient to do a post to an endpoint that requires login in the form of an HTTP cookie that identifies an account (this is o

5条回答
  •  生来不讨喜
    2020-11-22 10:22

    I had a similar problem and for my AspNetCore 3.1 application the other answers to this question were not working. I found that configuring a named HttpClient in my Startup.cs and using header propagation of the Cookie header worked perfectly. It also avoids all the concerns about proper disposition of your handler and client. Note if propagation of the request cookies is not what you need (sorry Op) you can set your own cookies when configuring the client factory.

    • I used this guide from Microsoft - Make HTTP requests using IHttpClientFactory in ASP.NET Core
    • Header propagation is covered in this section - Header propagation middleware

    Configure Services with IServiceCollection

    services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
    services.AddHeaderPropagation(options =>
    {
        options.Headers.Add("Cookie");
    });
    

    Configure with IApplicationBuilder

    builder.UseHeaderPropagation();
    
    • Inject the IHttpClientFactory into your controller or middleware.
    • Create your client using var client = clientFactory.CreateClient("MyNamedClient");

提交回复
热议问题