.net中好用的Http请求库

我们在使用.net 开发系统的时候,经常会遇到rest接口的调用,按照传统的方式,我们基本是使用HttpWebRequest或者WebClient,但是这样的话、我们会处理很多东西,代码量也就上来了,后来在.net 4.5提供了HttpClient这个类库,它相对于前面两个类,使用起来就更加的简洁方便,但是今天我们要说的另外两个第三方库:FlurlRestSharp

先说说我的业务场景,事情的起因是需要调用一个接口来同步数据,这个WebAPI接口是基于ABP开发的,接口提供者加了AbpAuthorize,需要登录才能调用,所以,这里需要先获取accessToken,添加到请求头才能调用数据接口。

Flurl

Flurl是一个简单易用的Http,想要了解更多详情请至官网https://flurl.dev/查看。首先来看看登录接口返回的数据格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"result": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJBc3BOZXQuSWRlbnRpdHkuU2VjdXJpdHlTdGFtcCI6ImM0ZmZmMDY1LTcxODMtMzU5MS1lYzUxLTM5ZWVhNTI3MTI4YSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkFkbWluIiwiaHR0cDovL3d3dy5hc3BuZXRib2lsZXJwbGF0ZS5jb20vaWRlbnRpdHkvY2xhaW1zL3RlbmFudElkIjoiMSIsInN1YiI6IjIiLCJqdGkiOiJhNjJkZDhmOC03MjBlLTQ2M2YtYjA4Mi1kMzk3YzY4NzUwYzciLCJpYXQiOjE1ODA2NTMxNjIsIm5iZiI6MTU4MDY1MzE2MiwiZXhwIjoxNTgwNzM5NTYyLCJpc3MiOiJKZXdlbHJ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zIEdUjA1/apD+dPNvs2tShapSWWx8xK0YRby40+Mu18Z6pkVDPKT1+1zkCJtBedz5UX0MT1pY8jU+OWKd9vPSVxsNAw==",
"expireInSeconds": 86400,
"userId": 2,
"authCode": 0
},
"targetUrl": null,
"success": true,
"error": null,
"unAuthorizedRequest": false,
"__abp": true
}

这时候,我们可以借助VS强大的粘贴功能,编辑->选择性粘贴->将JSON粘贴为类,最后的类格式如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class UserTokenDto
{
public Result result { get; set; }
public object targetUrl { get; set; }
public bool success { get; set; }
public object error { get; set; }
public bool unAuthorizedRequest { get; set; }
public bool __abp { get; set; }
}

public class Result
{
public string accessToken { get; set; }
public string encryptedAccessToken { get; set; }
public int expireInSeconds { get; set; }
public int userId { get; set; }
public int authCode { get; set; }
}

这时候,我们就可以调用登录接口了

1
2
var response =await "http://xxxxxx/api/TokenAuth/Authenticate".PostJsonAsync(new { usernameOrEmailAddress = "admin", password = "123qwe" }).ReceiveJson<UserTokenDto>();
return response.result.accessToken;

简单的两句代码就完成了发起请求和取返回值的操作。
那么接下来,我们就要调用数据同步接口了。因为ABP是使用的Bearer方式验证,正好``Flurl为我们提供了WithOAuthBearerToken方法,可以直接使用,如果是其他方式,那么可以自己在WithHeader中添加相应的请求头。我选择的当然是简单那的方式啦

1
var data= await "http://xxxxxx/api/services/app/PublicityItem/GetPublicityItemFirstUnsynchronized".WithOAuthBearerToken(response.result.accessToken).GetAsync().ReceiveJson<CertInfoDataDto>();

就这样简单的一句、就完成了接口的调用,是不是很方便呢?更多信息大概去官网了解吧。

RestSharp

首先 当然还是需要去浏览官网啦http://restsharp.org/,接下来,我们就试试用的RestSharp来完成上面Flurl的操作,首先还是第一步,获取accessToken

1
2
3
4
5
6
var client = new RestClient("http://bqp.natapp1.cc/api/");
var request = new RestRequest("TokenAuth/Authenticate", Method.POST);
var json = JsonConvert.SerializeObject(new { usernameOrEmailAddress = "admin", password = "123qwe" });
request.AddParameter("application/json", json, ParameterType.RequestBody);
var response = client.Execute(request);
var user = JsonConvert.DeserializeObject<UserTokenDto>(response.Content);

第二步调用数据同步接口

1
2
3
var restRequest = new RestRequest("services/app/PublicityItem/GetPublicityItemFirstUnsynchronized", Method.GET);
restRequest.AddHeader("Authorization", $"Bearer {user.result.accessToken}");
var restResponse = client.Execute(restRequest);

这里我就是手动在请求头中加入Authorization参数。

总结

经过一番简单的对比,我觉得还是Flurl更加的简洁方便,获取是我没有深入RestSharp的缘故吧,但是总的来说,还是比之前自带的类库还方便得多。那么更多详细功能,大家自行去探究吧。

You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×