1. 程式人生 > >(27)ASP.NET Core .NET標準REST庫Refit

(27)ASP.NET Core .NET標準REST庫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,後者根據使用者的需求對結果進行解析的過程。安裝元件命令列:

Install-Package refit

程式碼例子:

[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<IEnumerable<string>>> Get()
{
    var result = await new GitHubApi().GetUser();
    return new string[] { result.id.Value.ToString(), result.login };
}

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

 

 

2.API屬性

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

,例:

[Get("/users/list")]

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

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

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

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

請求URL還可以將替換塊繫結到自定義物件,例:

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

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

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

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

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

方法還可以傳遞自定義物件,把物件屬性追加到查詢字串引數當中,例如:

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

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

GroupListWithAttribute(4, params)

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

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

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

方法除了支援傳遞自定義物件查詢,還支援集合查詢的,例:

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

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

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

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

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

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

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

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

7.Body內容

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

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

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

Task CreateUser([Body(buffered: true)] User user);

7.1.JSON內容

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

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

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

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()
        }
    )});

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

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

7.2XML內容

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

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

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

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

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

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
                    }
                }
            }
        )
});

7.3.表單釋出(Form posts)

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

public interface IMeasurementProtocolApi
{
    [Post("/collect")]
    Task Collect([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
}
var data = new Dictionary<string, object> {
    {"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);

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

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);

8.設定請求頭

8.1靜態頭(Static headers)

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

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

通過將headers屬性應用於介面,還可以將靜態頭新增到API中的每個請求:

[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);
}

8.2動態頭(Dynamic headers)

如果需要在執行時設定頭的內容,則可以通過將頭屬性應用於引數來向請求新增具有動態值的頭:

[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"); 

8.3授權(動態頭redux)

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

class AuthenticatedHttpClientHandler : HttpClientHandler
{
    private readonly Func<Task<string>> getToken;
    public AuthenticatedHttpClientHandler(Func<Task<string>> 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);
    }
}

或者:

class AuthenticatedParameterizedHttpClientHandler : DelegatingHandler
    {
        readonly Func<HttpRequestMessage, Task<string>> getToken;
        public AuthenticatedParameterizedHttpClientHandler(Func<HttpRequestMessage, Task<string>> 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);
        }
    }

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

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();
}

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

參考文獻:
R