自定义实现httpclient

时间:2018-06-08 00:18:07

标签: asp.net-web-api asp.net-web-api2 httpclient asp.net-core-webapi

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

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

}

因为很多操作都会调用这些确切的代码行。我打算创建一个实现的HttpClient类,如下所示。此类的对象需要已初始化所有自定义实现。可以这样做吗?

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
}

1 个答案:

答案 0 :(得分:1)

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

例如

In [11]: places = ["PL", "pl", "Pl", "PLACE", "Place", "place"]

In [12]: mydata.Street_type
Out[12]:
0       PL
1       pl
2       Pl
3    PLACE
4    place
Name: Street_type, dtype: object

In [13]: mydata.Street_type.replace("(^|\b)({})(\b|$)".format("|".join(places)), "Place", regex=True)
Out[13]:
0    Place
1    Place
2    Place
3    Place
4    Place
Name: Street_type, dtype: object