httpclient 的自定义实现

Custom implementation of httpclient

我有一个 WebAPI,需要在请求中发送自定义身份验证令牌 header。

using (var client = new HttpClient()
{
     client.BaseAddress = new Uri("https://example.com");
     var request = new HttpRequestMessage(HttpMethod.Post, "/adfs/oauth2/authorize);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "<token>");
    ...
    ...
    //code removed for brevity

}

因为很多操作都将调用这些确切的代码行。我计划创建一个已实现的 class HttpClient,如下所示。此 class 的 object 需要已初始化所有自定义实现。这能做到吗?

public class MyHttpClient : HttpClient
{
    //how do I make sure the object of MyHttpClient will implicitly set all the desired properties (headers etc)
}


using (var client = new MyHttpClient()
{
   //client should come with all the properties initialized
}

您可以在派生的构造函数中添加默认属性 class。

例如

public class MyHttpClient : HttpClient {

    public MyHttpClient(): base() {
        BaseAddress = new Uri("https://example.com");
        DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "<token>");
        //...
        //...
        //code removed for brevity
    }
}