.net?core如何使用WebApiClientCore的示例代碼?
Admin 2023-09-15 群英技術(shù)資訊 1739 次瀏覽
今天就跟大家聊聊有關(guān)“.net?core如何使用WebApiClientCore的示例代碼?”的內(nèi)容,可能很多人都不太了解,為了讓大家認識和更進一步的了解,小編給大家總結(jié)了以下內(nèi)容,希望這篇“.net?core如何使用WebApiClientCore的示例代碼?”文章能對大家有幫助。1 配置文件中配置HttpApiOptions選項
配置示例
"IUserApi": {
"HttpHost": "http://www.webappiclient.com/",
"UseParameterPropertyValidate": false,
"UseReturnValuePropertyValidate": false,
"JsonSerializeOptions": {
"IgnoreNullValues": true,
"WriteIndented": false
}
}
2 Service注冊
示例
services
.ConfigureHttpApi<IUserApi>(Configuration.GetSection(nameof(IUserApi)))
.ConfigureHttpApi<IUserApi>(o =>
{
// 符合國情的不標(biāo)準(zhǔn)時間格式,有些接口就是這么要求必須不標(biāo)準(zhǔn)
o.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
});
HttpApiOptions詳細展示
/// <summary>
/// 表示HttpApi選項
/// </summary>
public class HttpApiOptions
{
/// <summary>
/// 獲取或設(shè)置Http服務(wù)完整主機域名
/// 例如http://www.abc.com/或http://www.abc.com/path/
/// 設(shè)置了HttpHost值,HttpHostAttribute將失效
/// </summary>
public Uri? HttpHost { get; set; }
/// <summary>
/// 獲取或設(shè)置是否使用的日志功能
/// </summary>
public bool UseLogging { get; set; } = true;
/// <summary>
/// 獲取或設(shè)置請求頭是否包含默認的UserAgent
/// </summary>
public bool UseDefaultUserAgent { get; set; } = true;
/// <summary>
/// 獲取或設(shè)置是否對參數(shù)的屬性值進行輸入有效性驗證
/// </summary>
public bool . { get; set; } = true;
/// <summary>
/// 獲取或設(shè)置是否對返回值的屬性值進行輸入有效性驗證
/// </summary>
public bool UseReturnValuePropertyValidate { get; set; } = true;
/// <summary>
/// 獲取json序列化選項
/// </summary>
public JsonSerializerOptions JsonSerializeOptions { get; } = CreateJsonSerializeOptions();
/// <summary>
/// 獲取json反序列化選項
/// </summary>
public JsonSerializerOptions JsonDeserializeOptions { get; } = CreateJsonDeserializeOptions();
/// <summary>
/// xml序列化選項
/// </summary>
public XmlWriterSettings XmlSerializeOptions { get; } = new XmlWriterSettings();
/// <summary>
/// xml反序列化選項
/// </summary>
public XmlReaderSettings XmlDeserializeOptions { get; } = new XmlReaderSettings();
/// <summary>
/// 獲取keyValue序列化選項
/// </summary>
public KeyValueSerializerOptions KeyValueSerializeOptions { get; } = new KeyValueSerializerOptions();
/// <summary>
/// 獲取自定義數(shù)據(jù)存儲的字典
/// </summary>
public Dictionary<object, object> Properties { get; } = new Dictionary<object, object>();
/// <summary>
/// 獲取接口的全局過濾器集合
/// </summary>
public IList<IApiFilter> GlobalFilters { get; } = new List<IApiFilter>();
/// <summary>
/// 創(chuàng)建序列化JsonSerializerOptions
/// </summary>
private static JsonSerializerOptions CreateJsonSerializeOptions()
{
return new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
}
/// <summary>
/// 創(chuàng)建反序列化JsonSerializerOptions
/// </summary>
/// <returns></returns>
private static JsonSerializerOptions CreateJsonDeserializeOptions()
{
var options = CreateJsonSerializeOptions();
options.Converters.Add(JsonCompatibleConverter.EnumReader);
options.Converters.Add(JsonCompatibleConverter.DateTimeReader);
return options;
}
}
Uri(url)拼接規(guī)則
所有的Uri拼接都是通過Uri(Uri baseUri, Uri relativeUri)這個構(gòu)造器生成。
帶/結(jié)尾的baseUri
http://a.com/ + b/c/d = http://a.com/b/c/dhttp://a.com/path1/ + b/c/d = http://a.com/path1/b/c/dhttp://a.com/path1/path2/ + b/c/d = http://a.com/path1/path2/b/c/d不帶/結(jié)尾的baseUri
http://a.com + b/c/d = http://a.com/b/c/dhttp://a.com/path1 + b/c/d = http://a.com/b/c/dhttp://a.com/path1/path2 + b/c/d = http://a.com/path1/b/c/d事實上http://a.com與http://a.com/是完全一樣的,他們的path都是/,所以才會表現(xiàn)一樣。為了避免低級錯誤的出現(xiàn),請使用的標(biāo)準(zhǔn)baseUri書寫方式,即使用/作為baseUri的結(jié)尾的第一種方式。
推薦使用自定義TokenProvider
public class TestTokenProvider : TokenProvider
{
private readonly IConfiguration _configuration;
public TestTokenProvider(IServiceProvider services,IConfiguration configuration) : base(services)
{
_configuration = configuration;
}
protected override Task<TokenResult> RefreshTokenAsync(IServiceProvider serviceProvider, string refresh_token)
{
return this.RefreshTokenAsync(serviceProvider, refresh_token);
}
protected override async Task<TokenResult> RequestTokenAsync(IServiceProvider serviceProvider)
{
LoginInput login = new LoginInput();
login.UserNameOrEmailAddress = "admin";
login.Password = "bb123456";
var result = await serviceProvider.GetRequiredService<ITestApi>().RequestToken(login).Retry(maxCount: 3);
return result;
}
}
TokenProvider的注冊
services.AddTokenProvider<ITestApi,TestTokenProvider>();
可以自定義OAuthTokenHandler官方定義是屬于http消息處理器,功能與OAuthTokenAttribute一樣,除此之外,如果因為意外的原因?qū)е路?wù)器仍然返回未授權(quán)(401狀態(tài)碼),其還會丟棄舊token,申請新token來重試一次請求。
OAuthToken在webapiclient中一般是保存在http請求的Header的Authrization
當(dāng)token在url中時我們需要自定義OAuthTokenHandler
class UriQueryOAuthTokenHandler : OAuthTokenHandler
{
/// <summary>
/// token應(yīng)用的http消息處理程序
/// </summary>
/// <param name="tokenProvider">token提供者</param>
public UriQueryOAuthTokenHandler(ITokenProvider tokenProvider)
: base(tokenProvider)
{
}
/// <summary>
/// 應(yīng)用token
/// </summary>
/// <param name="request"></param>
/// <param name="tokenResult"></param>
protected override void UseTokenResult(HttpRequestMessage request, TokenResult tokenResult)
{
// var builder = new UriBuilder(request.RequestUri);
// builder.Query += "mytoken=" + Uri.EscapeDataString(tokenResult.Access_token);
// request.RequestUri = builder.Uri;
var uriValue = new UriValue(request.RequestUri).AddQuery("myToken", tokenResult.Access_token);
request.RequestUri = uriValue.ToUri();
}
}
AddQuery是請求的的url中攜帶token的key
自定義OAuthTokenHandler的使用
services
.AddHttpApi<IUserApi>()
.AddOAuthTokenHandler((s, tp) => new UriQueryOAuthTokenHandler(tp));
//自定義TokoenProvider使用自定義OAuthTokenHandler
apiBulider.AddOAuthTokenHandler<UrlTokenHandler>((sp,token)=>
{
token=sp.GetRequiredService<TestTokenProvider>();
return new UrlTokenHandler(token);
},WebApiClientCore.Extensions.OAuths.TypeMatchMode.TypeOrBaseTypes);
OAuthToken可以定義在繼承IHttpApi的接口上也可以定義在接口的方法上
在使用自定義TokenProvier時要注意OAuthToken特性不要定義在具有請求token的Http請求定義上
Patch請求
json patch是為客戶端能夠局部更新服務(wù)端已存在的資源而設(shè)計的一種標(biāo)準(zhǔn)交互,在RFC6902里有詳細的介紹json patch,通俗來講有以下幾個要點:
聲明Patch方法
public interface IUserApi
{
[HttpPatch("api/users/{id}")]
Task<UserInfo> PatchAsync(string id, JsonPatchDocument<User> doc);
}
實例化JsonPatchDocument
var doc = new JsonPatchDocument<User>(); doc.Replace(item => item.Account, "laojiu"); doc.Replace(item => item.Email, "[email protected]");
請求內(nèi)容
PATCH /api/users/id001 HTTP/1.1
Host: localhost:6000
User-Agent: WebApiClientCore/1.0.0.0
Accept: application/json; q=0.01, application/xml; q=0.01
Content-Type: application/json-patch+json
[{"op":"replace","path":"/account","value":"laojiu"},{"op":"replace","path":"/email","value":"[email protected]"}]
異常處理
try
{
var model = await api.GetAsync();
}
catch (HttpRequestException ex) when (ex.InnerException is ApiInvalidConfigException configException)
{
// 請求配置異常
}
catch (HttpRequestException ex) when (ex.InnerException is ApiResponseStatusException statusException)
{
// 響應(yīng)狀態(tài)碼異常
}
catch (HttpRequestException ex) when (ex.InnerException is ApiException apiException)
{
// 抽象的api異常
}
catch (HttpRequestException ex) when (ex.InnerException is SocketException socketException)
{
// socket連接層異常
}
catch (HttpRequestException ex)
{
// 請求異常
}
catch (Exception ex)
{
// 異常
}
請求重試
使用ITask<>異步聲明,就有Retry的擴展,Retry的條件可以為捕獲到某種Exception或響應(yīng)模型符合某種條件。
GetNumberTemplateForEditOutput put = new GetNumberTemplateForEditOutput();
var res = await _testApi.GetForEdit(id).Retry(maxCount: 1).WhenCatchAsync<ApiResponseStatusException>(async p =>
{
if (p.StatusCode == HttpStatusCode.Unauthorized)
{
await Token();//當(dāng)http請求異常時報錯,重新請求一次,保證token一直有效
}
});
put = res.Result;
return put;
API接口處理
使用ITask<>異步聲明
[HttpHost("請求地址")]//請求地址域名
public interface ITestApi : IHttpApi
{
[OAuthToken]//權(quán)限
[JsonReturn]//設(shè)置返回格式
[HttpGet("/api/services/app/NumberingTemplate/GetForEdit")]//請求路徑
ITask<AjaxResponse<GetNumberTemplateForEditOutput>> GetForEdit([Required] string id);//請求參數(shù)聲明
[HttpPost("api/TokenAuth/Authenticate")]
ITask<string> RequestToken([JsonContent] AuthenticateModel login);
}
擴展類聲明
/// <summary>
/// WebApiClient擴展類
/// </summary>
public static class WebApiClientExentions
{
public static IServiceCollection AddWebApiClietHttp<THttp>(this IServiceCollection services, Action<HttpApiOptions>? options = null) where THttp : class, IHttpApi
{
HttpApiOptions option = new HttpApiOptions();
option.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
option.UseParameterPropertyValidate = true;
if(options != null)
{
options.Invoke(option);
}
services.AddHttpApi<THttp>().ConfigureHttpApi(p => p = option);
return services;
}
public static IServiceCollection AddWebApiClietHttp<THttp>(this IServiceCollection services,IConfiguration configuration) where THttp : class, IHttpApi
{
services.AddHttpApi<THttp>().ConfigureHttpApi((Microsoft.Extensions.Configuration.IConfiguration)configuration);
return services;
}
public static IServiceCollection AddWebApiClientHttpWithTokeProvider<THttp, TTokenProvider>(this IServiceCollection services, Action<HttpApiOptions>? options = null) where THttp : class, IHttpApi
where TTokenProvider : class, ITokenProvider
{
services.AddWebApiClietHttp<THttp>(options);
services.AddTokenProvider<THttp,TTokenProvider>();
return services;
}
public static IServiceCollection AddWebApiClientHttpWithTokeProvider<THttp, TTokenProvider>(this IServiceCollection services, IConfiguration configuration) where THttp : class, IHttpApi
where TTokenProvider : class, ITokenProvider
{
services.AddWebApiClietHttp<THttp>(configuration);
services.AddTokenProvider<THttp, TTokenProvider>();
return services;
}
}
擴展類使用
services.AddWebApiClientHttpWithTokeProvider<ITestApi, TestTokenProvider>();
關(guān)于“.net?core如何使用WebApiClientCore的示例代碼?”的內(nèi)容今天就到這,感謝各位的閱讀,大家可以動手實際看看,對大家加深理解更有幫助哦。如果想了解更多相關(guān)內(nèi)容的文章,關(guān)注我們,群英網(wǎng)絡(luò)小編每天都會為大家更新不同的知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:[email protected]進行舉報,并提供相關(guān)證據(jù),查實之后,將立刻刪除涉嫌侵權(quán)內(nèi)容。
猜你喜歡
在軟件開發(fā)過程中,有時候我們需要定時地檢查數(shù)據(jù)庫中的數(shù)據(jù),并在發(fā)現(xiàn)新增數(shù)據(jù)時觸發(fā)一個動作。為了實現(xiàn)這個需求,本文我們在?.Net?7?下進行一次簡單的演示。感興趣的可以了解一下
本文主要介紹了.net?core?3.1?Redis安裝和簡單使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
這篇文章主要介紹了ASP.NET?Core按用戶等級授權(quán),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
最近?chatgpt?很火,由于網(wǎng)頁版本限制了?ip,還得必須開代理,用起來比較麻煩,所以我嘗試用?maui?開發(fā)一個聊天小應(yīng)用,結(jié)合?chatgpt?的開放?api?來實現(xiàn),這篇文章主要介紹了使用?.NET?MAUI?開發(fā)?ChatGPT?客戶端,需要的朋友可以參考下
這篇文章主要為大家介紹了.Net執(zhí)行SQL存儲過程之易用輕量工具詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
推薦內(nèi)容
相關(guān)標(biāo)簽
成為群英會員,開啟智能安全云計算之旅
立即注冊關(guān)注或聯(lián)系群英網(wǎng)絡(luò)
7x24小時售前:400-678-4567
7x24小時售后:0668-2555666
24小時QQ客服
群英微信公眾號
CNNIC域名投訴舉報處理平臺
服務(wù)電話:010-58813000
服務(wù)郵箱:[email protected]
投訴與建議:0668-2555555
Copyright ? QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版權(quán)所有
增值電信經(jīng)營許可證 : B1.B2-20140078 ICP核準(zhǔn)(ICP備案)粵ICP備09006778號 域名注冊商資質(zhì) 粵 D3.1-20240008