我已经google了很多搜索我的问题的答案没有运气所以,让我们尝试,如果别人可以帮助我.
在进行一些验证后,我有一个Web Api 2操作来注册用户.如果一切正常,它将返回序列化用户,如果没有,则返回BadRequest响应中发送的错误消息.
我的问题是我无法得到错误发送的原因,客户端只是得到Bad Request错误消息.
这是代码的一部分:
> Web Api动作:
public async Task<IHttpActionResult> AddUser(NewUserDTO { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (!model.IdCliente.HasValue) { ModelState.AddModelError("","No existe el cliente"); return BadRequest(ModelState); } // do save stuff return Ok(TheModelFactory.Create(user)); }
>客户端功能:
public async Task<ApplicationUserDTO> AddUser(NewUserDTO dto) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_urlBase); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",Token); HttpContent content = new StringContent(JsonConvert.SerializeObject(dto)); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage responseMessage = await client.PostAsync("api/accounts/AddUser",content); if (responseMessage.IsSuccessStatusCode) { var responseJson = await responseMessage.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<ApplicationUserDTO>(responseJson); } else MessageBox.Show(responseMessage.Content.ReadAsStringAsync().Result); return user; } }
有人可以帮忙吗?
编辑:
> DTO:
[Serializable] public class NewUserDTO { public int? IdCliente { get; set; } [required] public string UserName { get; set; } [required] public string Email { get; set; } public string Role { get; set; } public string Password { get; set; } }
无论如何… dto被正确发送到api nut,这是你要求的序列化dto:
"{\"IdCliente\":null,\"UserName\":\"Toni\",\"Email\":\"soft@moreno-csa.com\",\"Role\":\"Filtra\",\"Password\":\"TONI\"}"
解决方法
你检查过web.config httpErrors部分了吗?
我遇到了同样的问题,因为我的web.config看起来像这样
<httpErrors errorMode="Custom" existingResponse="Replace"> <clear /> <error statusCode="404" path="~/Error/NotFound" responseMode="ExecuteURL" /> <error statusCode="403" path="~/Error/AccessDenied" responseMode="ExecuteURL" /> <error statusCode="500" path="~/Error/ServerError" responseMode="ExecuteURL" /> </httpErrors>
您必须确保existingResponse设置为PassThrough
<httpErrors errorMode="Custom" existingResponse="PassThrough"> <clear /> <error statusCode="404" path="~/Error/NotFound" responseMode="ExecuteURL" /> <error statusCode="403" path="~/Error/AccessDenied" responseMode="ExecuteURL" /> <error statusCode="500" path="~/Error/ServerError" responseMode="ExecuteURL" /> </httpErrors>
不确定它是否会对你有帮助,但要试一试.