在Blazor客户端中使用HTTP时,只有在响应为成功响应时才起作用,但是如果未找到响应或响应不正确,它将给出异常并且无法完成代码.
When using the HTTP in Blazor client side it only works if the response is a success response, but if it is not found or bad response it gives exception and doesn't complete the code.
即使请求未成功,我也想解析我在响应中发送的对象,我的意思是400或404,我发送了一个带有错误列表的对象,所以我需要获取它.
I want to parse the object I send in the response even if the request is not successful I mean 400 or 404, I send an object with error list so I need to get it.
在控制台中出现错误,即请求未成功.
It gives me error in the console that the request is not successful.
如果我将请求设置为(OK),那么它就可以了,但是我需要发送400个状态为"RequestResult"的对象,我该如何处理呢?
If I make the request to be (OK) then it works, but I need to send 400 status with the object "RequestResult" how I could manage this?
var result = await _httpClient.PostJsonAsync<RequestResult>("api/account/auth", authModel); if (result.Successful) { await _localStorage.SetItemAsync("Token", authModel.SecurityToken); AuthData.AuthToken= result.Token; ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(result.Token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token); return result; } return result;这是当我将BadRequest更改为Ok时的控制器代码
and this is the controller code when i change BadRequest to Ok it work
public IActionResult Post([FromBody]AuthModel model) { var res = _authManager.SignInUser(model); if (!res.Successful) { return BadRequest(new RequestResult { Successful = false, Errors = new List<string>() { res?.errors } }); } return Ok(new RequestResult { Successful = true ,Token=res.access_token}); }推荐答案
PostJsonAsync以这种方式工作.如果无法解析内容,将引发异常.这是建议的解决方法: 必须使用using语句:using System.Text.Json;
PostJsonAsync works this way. It will throw an exception if the content cannot be parsed. Here is a suggested workaround: Required using statement: using System.Text.Json;
var response = await _httpClient.PostAsync("api/account/auth", authModel); if (response.IsSuccessStatusCode) { //parse result as following using (var sr = await response.Content.ReadAsStreamAsync()) { var parsedResult = JsonSerializer.DeserializeAsync<RecipeDetailDto>(sr); } } else { //If the bad request content/body is a json object //parse error content using (var sr = await response.Content.ReadAsStreamAsync()) { //If the bad request content is a json //var parsedErrorResult = JsonSerializer.DeserializeAsync<yourErroObjset>(sr); } //OR if the content is string var errorResult = await response.Content.ReadAsString(); }没有证明它,但它应该为您提供如何实现这一目标的背景.
Did not testet it, but it should give you the context how to approach this.
更多推荐
blazor httpClient.PostJsonAsync状态码异常
发布评论