在ASP.NET Core 中實現RESTFull庫的Refit

1.簡介

Refit

是一個受到Square的Retrofit庫(Java)啟發的自動類型安全REST庫。通過HttpClient網絡請求(POST,GET,PUT,DELETE等封裝)把REST API返回的數據轉化為POCO(Plain Ordinary C# Object,簡單C#對象) to JSON。我們的應用程序通過Refit請求網絡,實際上是使用Refit接口層封裝請求參數、Header、Url等信息,之後由HttpClient完成後續的請求操作,在服務端返回數據之後,HttpClient將原始的結果交給Refit,後者根據用戶的需求對結果進行解析的過程。安裝組件命令行:

<code>Install-Package refit/<code>

代碼例子:

<code>[Headers("User-Agent: Refit Integration Tests")]//這裡因為目標源是GitHubApi,所以一定要加入這個靜態請求標頭信息,讓其這是一個測試請求,不然會返回數據異常。
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<user> GetUser(string user);
}
public class GitHubApi
{
public async Task<user> GetUser()
{
var gitHubApi = RestService.For<igithubapi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
return octocat;
}
}
public class User
{
public string login { get; set; }
public int? id { get; set; }
public string url { get; set; }
}
[HttpGet]
public async Task<actionresult>>> Get()

{
var result = await new GitHubApi().GetUser();
return new string[] { result.id.Value.ToString(), result.login };
}/<actionresult>/<igithubapi>/<user>/<user>/<code>

注:接口中Headers、Get這些屬性叫做Refit的特性。定義上面的一個IGitHubApi的REST API接口,該接口定義了一個函數GetUser,該函數會通過HTTP GET請求去訪問服務器的/users/{user}路徑把返回的結果封裝為User POCO對象並返回。其中URL路徑中的{user}的值為GetUser函數中的參數user的取值,這裡賦值為octocat。然後通過RestService類來生成一個IGitHubApi接口的實現並供HttpClient調用。

在ASP.NET Core 中實現RESTFull庫的Refit


2.API屬性

每個方法必須具有提供請求URL和HTTP屬性。HTTP屬性有六個內置註釋:Get, Post, Put, Delete, Patch and Head,例:

<code>[Get("/users/list")]/<code>

您還可以在請求URL中指定查詢參數:

<code>[Get("/users/list?sort=desc")]/<code>

還可以使用相對URL上的替換塊和參數來動態請求資源。替換塊是由{and,即&}包圍的字母數字字符串。如果參數名稱與URL路徑中的名稱不匹配,請使用AliasAs屬性,例:

<code>[Get("/group/{id}/users")]
Task<list>> GroupList([AliasAs("id")] int groupId);/<list>/<code>

請求URL還可以將替換塊綁定到自定義對象,例:

<code>[Get("/group/{request.groupId}/users/{request.userId}")]
Task<list>> GroupList(UserGroupRequest request);
class UserGroupRequest{
int groupId { get;set; }
int userId { get;set; }
}/<list>/<code>

未指定為URL替換的參數將自動用作查詢參數。這與Retrofit不同,在Retrofit中,必須明確指定所有參數,例:

<code>[Get("/group/{id}/users")]
Task<list>> GroupList([AliasAs("id")] int groupId, [AliasAs("sort")] string sortOrder);

GroupList(4, "desc");/<list>/<code>

輸出結果:"/group/4/users?sort=desc"

3.動態查詢字符串參數(Dynamic Querystring Parameters)

方法還可以傳遞自定義對象,把對象屬性追加到查詢字符串參數當中,例如:

<code>public class MyQueryParams
{
[AliasAs("order")]
public string SortOrder { get; set; }
public int Limit { get; set; }
}
[Get("/group/{id}/users")]
Task<list>> GroupList([AliasAs("id")] int groupId, MyQueryParams params);
[Get("/group/{id}/users")]
Task<list>> GroupListWithAttribute([AliasAs("id")] int groupId, [Query(".","search")]MyQueryParams params);
params.SortOrder = "desc";
params.Limit = 10;
GroupList(4, params)/<list>/<list>/<code>

輸出結果:"/group/4/users?order=desc&Limit=10"

<code>GroupListWithAttribute(4, params)/<code>

輸出結果:"/group/4/users?search.order=desc&search.Limit=10"您還可以使用[Query]指定querystring參數,並將其在非GET請求中扁平化,類似於:

<code>[Post("/statuses/update.json")]
Task<tweet> PostTweet([Query]TweetParams params);/<tweet>/<code>

5.集合作為查詢字符串參數(Collections as Querystring Parameters)

方法除了支持傳遞自定義對象查詢,還支持集合查詢的,例:

<code>[Get("/users/list")]
Task Search([Query(CollectionFormat.Multi)]int[] ages);
Search(new [] {10, 20, 30})/<code>

輸出結果:"/users/list?ages=10&ages=20&ages=30"

<code>[Get("/users/list")]
Task Search([Query(CollectionFormat.Csv)]int[] ages);
Search(new [] {10, 20, 30})/<code>

輸出結果:"/users/list?ages=10%2C20%2C30"

6.轉義符查詢字符串參數(Unescape Querystring Parameters)

使用QueryUriFormat屬性指定查詢參數是否應轉義網址,例:

<code>[Get("/query")]
[QueryUriFormat(UriFormat.Unescaped)]
Task Query(string q);
Query("Select+Id,Name+From+Account")/<code>

輸出結果:"/query?q=Select+Id,Name+From+Account"

7.Body內容

通過使用Body屬性,可以把自定義對象參數追加到HTTP請求Body當中。

<code>[Post("/users/new")]
Task CreateUser([Body] User user)/<code>

根據參數的類型,提供Body數據有四種可能性:●如果類型為Stream,則內容將通過StreamContent流形式傳輸。●如果類型為string,則字符串將直接用作內容,除非[Body(BodySerializationMethod.Json)]設置了字符串,否則將其作為StringContent。●如果參數具有屬性[Body(BodySerializationMethod.UrlEncoded)],則內容將被URL編碼。●對於所有其他類型,將使用RefitSettings中指定的內容序列化程序將對象序列化(默認為JSON)。●緩衝和Content-Length頭默認情況下,Refit重新調整流式傳輸正文內容而不緩衝它。例如,這意味著您可以從磁盤流式傳輸文件,而不會產生將整個文件加載到內存中的開銷。這樣做的缺點是沒有在請求上設置內容長度頭(Content-Length)。如果您的API需要您隨請求發送一個內容長度頭,您可以通過將[Body]屬性的緩衝參數設置為true來禁用此流行為:

<code>Task CreateUser([Body(buffered: true)] User user);/<code>

7.1.JSON內容

使用Json.NET對JSON請求和響應進行序列化/反序列化。默認情況下,Refit將使用可以通過設置Newtonsoft.Json.JsonConvert.DefaultSettings進行配置的序列化器設置:

<code>JsonConvert.DefaultSettings =
() => new JsonSerializerSettings() {
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = {new StringEnumConverter()}
};
//Serialized as: {"day":"Saturday"}
await PostSomeStuff(new { Day = DayOfWeek.Saturday });/<code>

由於默認靜態配置是全局設置,它們將影響您的整個應用程序。有時候我們只想要對某些特定API進行設置,您可以選擇使用RefitSettings屬性,以允許您指定所需的序列化程序進行設置,這使您可以為單獨的API設置不同的序列化程序設置:

<code>var gitHubApi = RestService.For<igithubapi>("https://api.github.com",
new RefitSettings {
ContentSerializer = new JsonContentSerializer(
new JsonSerializerSettings {
ContractResolver = new SnakeCasePropertyNamesContractResolver()
}
)});
var otherApi = RestService.For<iotherapi>("https://api.example.com",
new RefitSettings {
ContentSerializer = new JsonContentSerializer(
new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
)});/<iotherapi>/<igithubapi>/<code>

還可以使用Json.NET的JsonProperty屬性來自定義屬性序列化/反序列化:

<code>public class Foo
{
//像[AliasAs(“ b”)]一樣會在表單中發佈
[JsonProperty(PropertyName="b")]
public string Bar { get; set; }
} /<code>

7.2XML內容

XML請求和響應使用System.XML.Serialization.XmlSerializer進行序列化/反序列化。默認情況下,Refit只會使用JSON將內容序列化,若要使用XML內容,請將ContentSerializer配置為使用XmlContentSerializer:

<code>var gitHubApi = RestService.For<ixmlapi>("https://www.w3.org/XML",
new RefitSettings {
ContentSerializer = new XmlContentSerializer()
});/<ixmlapi>/<code>

屬性序列化/反序列化可以使用System.Xml.serialization命名空間中的屬性進行自定義:

<code>public class Foo
{
[XmlElement(Namespace = "https://www.w3.org/XML")]
public string Bar { get; set; }
}/<code>

System.Xml.Serialization.XmlSerializer提供了許多序列化選項,可以通過向XmlContentSerializer構造函數提供XmlContentSerializer設置來設置這些選項:

<code>var gitHubApi = RestService.For<ixmlapi>("https://www.w3.org/XML",
new RefitSettings {
ContentSerializer = new XmlContentSerializer(
new XmlContentSerializerSettings
{
XmlReaderWriterSettings = new XmlReaderWriterSettings()
{
ReaderSettings = new XmlReaderSettings
{
IgnoreWhitespace = true
}
}

}
)
});/<ixmlapi>/<code>

7.3.表單發佈(Form posts)

對於以表單形式發佈(即序列化為application/x-www-form-urlencoded)的API,請使用初始化Body屬性BodySerializationMethod.UrlEncoded屬性,參數可以是IDictionary字典,例:

<code>public interface IMeasurementProtocolApi
{
[Post("/collect")]
Task Collect([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string> data);
}
var data = new Dictionary<string> {
{"v", 1},
{"tid", "UA-1234-5"},
{"cid", new Guid("d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c")},
{"t", "event"},
};
// Serialized as: v=1&tid=UA-1234-5&cid=d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c&t=event
await api.Collect(data);/<string>/<string>/<code>

如果我們傳遞對象跟請求表單中字段名稱不一致時,可在對象屬性名稱上加入[AliasAs("你定義字段名稱")] 屬性,那麼加入屬性的對象字段都將會被序列化為請求中的表單字段:

<code>public interface IMeasurementProtocolApi
{
[Post("/collect")]
Task Collect([Body(BodySerializationMethod.UrlEncoded)] Measurement measurement);
}
public class Measurement
{
// Properties can be read-only and [AliasAs] isn't required
public int v { get { return 1; } }
[AliasAs("tid")]
public string WebPropertyId { get; set; }
[AliasAs("cid")]
public Guid ClientId { get; set; }
[AliasAs("t")]
public string Type { get; set; }

public object IgnoreMe { private get; set; }
}
var measurement = new Measurement {
WebPropertyId = "UA-1234-5",
ClientId = new Guid("d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c"),
Type = "event"
};
// Serialized as: v=1&tid=UA-1234-5&cid=d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c&t=event
await api.Collect(measurement);/<code>

8.設置請求頭

8.1靜態頭(Static headers)

您可以為將headers屬性應用於方法的請求設置一個或多個靜態請求頭:

<code>[Headers("User-Agent: Awesome Octocat App")]
[Get("/users/{user}")]
Task<user> GetUser(string user);/<user>/<code>

通過將headers屬性應用於接口,還可以將靜態頭添加到API中的每個請求:

<code>[Headers("User-Agent: Awesome Octocat App")]
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<user> GetUser(string user);
[Post("/users/new")]
Task CreateUser([Body] User user);
}/<user>/<code>

8.2動態頭(Dynamic headers)

如果需要在運行時設置頭的內容,則可以通過將頭屬性應用於參數來向請求添加具有動態值的頭:

<code>[Get("/users/{user}")]
Task<user> GetUser(string user, [Header("Authorization")] string authorization);
// Will add the header "Authorization: token OAUTH-TOKEN" to the request
var user = await GetUser("octocat", "token OAUTH-TOKEN"); /<user>/<code>

使用頭的最常見原因是為了授權。而現在大多數API使用一些oAuth風格的訪問令牌,這些訪問令牌會過期,刷新壽命更長的令牌。封裝這些類型的令牌使用的一種方法是,可以插入自定義的HttpClientHandler。這樣做有兩個類:一個是AuthenticatedHttpClientHandler,它接受一個Func<task>>參數,在這個參數中可以生成簽名,而不必知道請求。另一個是authenticatedparameteredhttpclienthandler,它接受一個Func<httprequestmessage>>參數,其中籤名需要有關請求的信息(參見前面關於Twitter的API的註釋),例如:/<httprequestmessage>/<task>

<code>class AuthenticatedHttpClientHandler : HttpClientHandler
{
private readonly Func<task>> getToken;
public AuthenticatedHttpClientHandler(Func<task>> getToken)
{
if (getToken == null) throw new ArgumentNullException(nameof(getToken));
this.getToken = getToken;
}
protected override async Task<httpresponsemessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null)
{
var token = await getToken().ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}/<httpresponsemessage>/<task>/<task>/<code>

或者:

<code>class AuthenticatedParameterizedHttpClientHandler : DelegatingHandler
{
readonly Func<httprequestmessage>> getToken;
public AuthenticatedParameterizedHttpClientHandler(Func<httprequestmessage>> getToken, HttpMessageHandler innerHandler = null)
: base(innerHandler ?? new HttpClientHandler())
{
this.getToken = getToken ?? throw new ArgumentNullException(nameof(getToken));
}


protected override async Task<httpresponsemessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null)
{
var token = await getToken(request).ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}/<httpresponsemessage>/<httprequestmessage>/<httprequestmessage>/<code>

雖然HttpClient包含一個幾乎相同的方法簽名,但使用方式不同。重新安裝未調用HttpClient.SendAsync。必須改為修改HttpClientHandler。此類的用法與此類似(示例使用ADAL庫來管理自動令牌刷新,但主體用於Xamarin.Auth或任何其他庫:

<code>class LoginViewModel
{
AuthenticationContext context = new AuthenticationContext(...);
private async Task<string> GetToken()
{
// The AcquireTokenAsync call will prompt with a UI if necessary
// Or otherwise silently use a refresh token to return
// a valid access token
var token = await context.AcquireTokenAsync("http://my.service.uri/app", "clientId", new Uri("callback://complete"));
return token;
}
public async Task LoginAndCallApi()
{
var api = RestService.For<imyrestservice>(new HttpClient(new AuthenticatedHttpClientHandler(GetToken)) { BaseAddress = new Uri("https://the.end.point/") });
var location = await api.GetLocationOfRebelBase();
}
}
interface IMyRestService
{
[Get("/getPublicInfo")]
Task<foobar> SomePublicMethod();
[Get("/secretStuff")]
[Headers("Authorization: Bearer")]
Task<location> GetLocationOfRebelBase();
}/<location>/<foobar>/<imyrestservice>/<string>/<code>

在上面的示例中,每當調用需要身份驗證的方法時,AuthenticatedHttpClientHandler將嘗試獲取新的訪問令牌。由應用程序提供,檢查現有訪問令牌的過期時間,並在需要時獲取新的訪問令牌。


分享到:


相關文章: