为何Postman与.NET MAUI发送相同API请求返回不同响应?
Postman与.NET MAUI调用同一登录API返回不同验证响应的问题
使用Postman和.NET MAUI应用调用同一登录API时,返回的验证错误响应不一致。该API端点负责验证邮箱和密码字段,Postman能返回所有验证错误,而.NET MAUI仅返回单条错误信息。
API控制器实现
以下是处理登录请求的API控制器相关代码段:
[ApiController] [ApiVersion(ApiVersions.V1)] [Route("api/v{version:apiVersion}/users")] public class UsersController (ISender sender, IMapper mapper) : ControllerBase { [HttpPost("login")] public async Task<IActionResult> Login([FromBody] LogInUserRequest request, CancellationToken cancellationToken) { var command = new LogInUserCommand(request.Email, request.Password); Result<string> result = await sender.Send(command, cancellationToken); if (result.IsFailure) { return Unauthorized(result.Error); } var response = new AccessTokenResponse(result.Value); return Ok(response); } }
API详情
- 端点:domain.com/api/v1/users/login
- 请求方法:POST
- Content-Type: application/json
请求体:
{ "email": "", "password": "" }
Postman响应
使用Postman发送请求时,收到包含多条验证信息的详细错误响应:
{ "type": "ValidationFailure", "title": "Validation error", "status": 400, "detail": "One or more validation errors has occurred", "errors": [ { "propertyName": "Email", "errorMessage": "'Email' must not be empty." }, { "propertyName": "Email", "errorMessage": "'Email' is not a valid email address." }, { "propertyName": "Password", "errorMessage": "'Password' must not be empty." }, { "propertyName": "Password", "errorMessage": "The length of 'Password' must be at least 6 characters. You entered 0 characters." } ] }
.NET MAUI响应
使用.NET MAUI应用通过HttpClient发送同一请求时,响应内容更简略,仅返回一条验证错误信息:
{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", "title": "One or more validation errors occurred.", "status": 400, "errors": { "Email": ["The Email field is required."] }, "traceId": "00-bc587b4c97e7b25236f0e375e0b4bc4a-e7b5ce673a92e452-00" }
.NET MAUI实现代码
以下是.NET MAUI应用中使用的代码:
public class AccountService(IHttpClientFactory httpClientFactory) { public async Task<Result<AccessTokenResponse>> LoginAsync(LogInUserRequest model) { using HttpClient client = httpClientFactory.CreateClient("SpardaApiClient"); try { var content = new StringContent(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json"); var response = await client.PostAsync($"users/login", content); if (response.IsSuccessStatusCode) { var responseData = await response.Content.ReadFromJsonAsync<AccessTokenResponse>(); return Result.Success<AccessTokenResponse>(responseData); } var errorContent = await response.Content.ReadAsStringAsync(); var result = HandleErrorResponse(errorContent, response.StatusCode); return result; } catch (Exception ex) { return Result.Failure<AccessTokenResponse>(Error.Validation()); } } }
疑问
是什么原因导致API对Postman和.NET MAUI发送的相同请求返回不同响应?Postman与HttpClient在请求处理或响应处理上是否存在已知差异可以解释这种不一致?恳请提供相关见解或建议!
内容的提问来源于stack exchange,提问作者Karwan E. Othman
相关产品推荐
相关产品推荐

