我正在将WebApi和Xamarin Forms用于移动应用程序。我正在使用WebApi的内置用户身份验证/帐户功能,但是我不确定如何解析来自具有ModelState错误的BadRequest响应中的错误。
AccountController当前具有:
if (!ModelState.IsValid)
{
logger.Info("ModelState not IsValid");
logger.Error(ModelState.ToString);
return BadRequest(ModelState);
}
这将返回任何模型状态错误(电子邮件不正确,密码不匹配等)
在我的客户端代码中,我有这个
注册帐户方法:
var response = await repository.PostAsync<SignUpModel>
(builder.ToString(), model, "");
存储库:
public async Task<T> PostAsync<T>(string uri, T data, string authToken = "")
{
try
{
HttpClient httpClient = CreateHttpClient(authToken);
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string jsonResult = string.Empty;
var responseMessage = await httpClient.PostAsync(uri, content);
if (responseMessage.IsSuccessStatusCode)
{
jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<T>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else if (responseMessage.StatusCode == HttpStatusCode.PreconditionFailed)
{
throw new Exception(responseMessage.ReasonPhrase);
}
else
{
throw new Exception(responseMessage.StatusCode.ToString());
}
}
catch (Exception e)
{
throw e;
}
}
SignUpModel:
public class SignUpPageModel
{
public int MobileNumber { get; set; }
public string FirstName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
我想捕获ModelState错误,然后向用户显示有关他们需要解决的问题的消息。