我如何获得Refit.ApiException的内容?
根据内容的内容,我想让用户知道如何继续.所以我看到抛出的异常有以下内容......
内容"{\"error \":\"invalid_grant \",\"error_description \":\"用户名或密码不正确.\"}"
问题是,我该如何访问?
我有一个应用程序请求经过身份验证的服务,需要通过access_token.
我的想法是在过期时使用 Polly 重试access_token。
我在 .NET Core 3.1 应用程序中使用 Refit (v5.1.67) 和 Polly (v7.2.1)。
服务注册如下:
services.AddTransient<ExampleDelegatingHandler>();
IAsyncPolicy<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
.Handle<ApiException>()
.RetryAsync(1, (response, retryCount) =>
{
System.Diagnostics.Debug.WriteLine($"Polly Retry => Count: {retryCount}");
});
services.AddRefitClient<TwitterApi>()
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://api.twitter.com/");
})
.AddHttpMessageHandler<ExampleDelegatingHandler>()
.AddPolicyHandler((sp, req) =>
{
//this policy does not works, because the exception is not catched on
//"Microsoft.Extensions.Http.PolicyHttpMessageHandler" (DelegatingHandler)
return retryPolicy;
});
Run Code Online (Sandbox Code Playgroud)
public interface TwitterApi
{
[Get("/2/users")]
Task<string> GetUsers();
}
Run Code Online (Sandbox Code Playgroud)
public class ExampleDelegatingHandler : DelegatingHandler …Run Code Online (Sandbox Code Playgroud) 我正在使用带有Refit的multipart.我尝试为我的服务上传个人资料图片,邮递员生成的代码看起来像这样
var client = new RestClient("http://api.example.com/api/users/1");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxx");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\nput\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_picture\"; filename=\"ic_default_avatar.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)
然后我像这样构建Refit方法
[Multipart]
[Post("/users/{id}")]
IObservable<BaseResponse<User>> UpdateProfilePicture(int id,[AliasAs("profile_picture")] byte[] profilePicture,[AliasAs("_method")]string method="put");
Run Code Online (Sandbox Code Playgroud)
如果我使用byte[]或ByteArrayPart它将抛出异常
{System.Net.Http.HttpRequestException:发送请求时发生错误---> System.Net.WebException:获取响应流时出错(chunked Read2):ReceiveFailure ---> System.Exception:at System.Net.WebConnection .HandleError(System.Net.WebExceptionStatus st,System.Exception e,System.String where)[0x00031] in:0 at System.Net.WebConnection.Read(System.Net.HttpWebRequest request,System.Byte [] buffer,System .Int32 offset,System.Int32 size)[0x000d2] in:0,System.Net.WebConnectionStream.ReadAll()[0x0010e] in:0,System.Net.HttpWebResponse.ReadAll()[0x00011] in:0 at System. Net.HttpWebRequest.CheckFinalStatus(System.Net.WebAsyncResult result)[0x001d6] in:0,System.Net.HttpWebRequest.SetResponseData(System.Net.WebConnectionData data)[0x0013e] in:0,System.Net.WebConnection.ReadDone( System.IAsyncResult结果)[0x0024d] in:0,System.Net.Sockets.SocketAsyncResult + <> c.b__27_0(System.Object …
我正在调查改装库并评估我是否值得集成到我的项目中。
假设我有一个接受POST带有特定合同的消息的控制器:
[Route("api/[controller]")]
[ApiController]
public class KeepAliveController : ControllerBase
{
[HttpPost]
public IActionResult Post(KeepAliveContract keepAliveContract)
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
根据我从refit文档中的理解,我必须创建一个界面。让我们称之为IKeepAliveService。它看起来像这样:
public interface IKeepAliveService
{
[Post("api/keepalive")]
Task SendKeepAliveAsync(KeepAliveContract keepAliveContract);
}
Run Code Online (Sandbox Code Playgroud)
这种做事方式会导致潜在的运行时错误,如果我PostAttribute在签名本身或签名中弄乱了路由。
题
有没有办法从现有控制器中自动生成这个接口,从而降低出现错误的风险?
我有一个 .Net Core Razor 页面应用程序,它尝试使用使用 Refit 创建的类库调用 .Net Core API。
我创建了一个 Refit API 接口,该接口使用以枚举作为属性类型之一的模型。
这是API端的接口片段:IPaymentAPIinterface
[Post("/recharge")]
Task<string> Recharge([Body] RechargeRequest request);
Run Code Online (Sandbox Code Playgroud)
这是请求模型: 该模型包含一个简单的 enum ELicenseType。
public class RechargeRequest
{
public ELicenseType LicenseType{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
EL 许可证类型:
public enum ELicenseType
{
NotSpecified = 0,
Standard = 1,
Commercial = 2
}
Run Code Online (Sandbox Code Playgroud)
控制器中的API实现:
[HttpPost("recharge")]
public async Task<IActionResult> Recharge(
[FromBody] RechargeRequest request)
{
Recharge result = await _mediator.Send(_mapper.Map<RechargeCommand>(request));
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
调用此 Recharge 方法时,Refit 会抛出 ValidationApiException:
ValidationApiException: Response status …Run Code Online (Sandbox Code Playgroud) 我正在使用 Refit 使用 asp.net core 2.2 中的 Typed Client 调用 API,该 API 当前使用我们的配置选项中的单个 BaseAddress 进行引导:
services.AddRefitClient<IMyApi>()
.ConfigureHttpClient(c => { c.BaseAddress = new Uri(myApiOptions.BaseAddress);})
.ConfigurePrimaryHttpMessageHandler(() => NoSslValidationHandler)
.AddPolicyHandler(pollyOptions);
Run Code Online (Sandbox Code Playgroud)
在我们的配置 json 中:
"MyApiOptions": {
"BaseAddress": "https://server1.domain.com",
}
Run Code Online (Sandbox Code Playgroud)
在我们的 IMyApi 界面中:
public IMyAPi interface {
[Get("/api/v1/question/")]
Task<IEnumerable<QuestionResponse>> GetQuestionsAsync([AliasAs("document_type")]string projectId);
}
Run Code Online (Sandbox Code Playgroud)
当前服务示例:
public class MyProject {
private IMyApi _myApi;
public MyProject (IMyApi myApi) {
_myApi = myApi;
}
public Response DoSomething(string projectId) {
return _myApi.GetQuestionsAsync(projectId);
}
}
Run Code Online (Sandbox Code Playgroud)
我现在需要在运行时根据数据使用不同的 BaseAddresses。我的理解是 Refit 将 HttpClient 的单个实例添加到 DI …
我正在使用 Refit 生成 Web 服务的客户端。
我的Web API的所有URL都是这样的:
https://service.com/api/v3/datasets?api_key=XXXXXXX
如您所见,API 密钥是在查询字符串而不是标头中指定的。
我希望 Refit 自动提供我的访问令牌作为查询字符串的一部分,而无需在我的服务界面中指定它。
我查看了文档,但还没有找到一种方法。
我将 Refit 用于 RestAPI。我需要创建相同的查询字符串api/item?c[]=14&c[]=74
在改装界面中我创建了方法
[Get("/item")]
Task<TendersResponse> GetTenders([AliasAs("c")]List<string> categories=null);
Run Code Online (Sandbox Code Playgroud)
并创建 CustomParameterFormatter
string query = string.Join("&c[]=", values);
Run Code Online (Sandbox Code Playgroud)
CustomParameterFormatter 生成的字符串 14&c[]=74
但是 Refit 编码参数和生成的 url api/item?c%5B%5D=14%26c%5B%5D%3D74
如何禁用此功能?
我正在使用我的Xamarin表单项目的Refit库来发送API请求.它工作得很好,但在访问令牌到期时会出现问题.
当访问令牌到期时,我从服务器收到401错误,如预期的那样.然后我打电话给Identity Server发出新的访问令牌,但我很难重新提交API请求.我仍然有未经授权的错误.感谢一些帮助.
我创建了一个AuthenticatedHttpClientHandler类来处理令牌.
public class AuthenticatedHttpClientHandler : HttpClientHandler
{
private readonly string _token;
public AuthenticatedHttpClientHandler(string token )
{
_token = token;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var auth = request.Headers.Authorization;
if (auth != null && !string.IsNullOrWhiteSpace(_token))
{
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, _token);
}
else
{
request.Headers.Remove("Authorization");
}
var result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized )
{
IdSrvApiService idsrvApiService = new IdSrvApiService();
RefreshTokenService refreshTokneService = new RefreshTokenService(idsrvApiService);
if( Settings.RefreshToken != ""){
var …Run Code Online (Sandbox Code Playgroud) 有没有办法使用Refit动态输入参数?
我的 Refit 界面中有以下代码:
[Get("/click?{parm}")]
Task<ApiResponse<TAny>> SaveClick(string parm);
Run Code Online (Sandbox Code Playgroud)
parm 的值为:
"id=1234&x=567"
Run Code Online (Sandbox Code Playgroud)
我的路线:
[HttpGet]
[Route("click")]
public void test ([FromQuery] string id)
{
Ok("Ok");
}
Run Code Online (Sandbox Code Playgroud)
我得到的只是 id 参数的值为空。预期结果将是一个值为“ 1234 ”的字符串
有什么帮助吗:D?