【发布时间】:2014-08-17 00:38:52
【问题描述】:
我正在尝试在我正在构建的 iOS 应用程序中处理 ModelState 问题。当我想注册用户时,我会将他们的详细信息发送到以下方法:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
我在我的 iOS 应用程序 (Swift) 中使用以下方法读取 JSON 响应:
func register(user:RegisterModel, successClosure: (() -> ())?, failureClosure: (() -> ())?) {
let manager = AFHTTPRequestOperationManager()
let registerUrl = XXXX
manager.POST( registerUrl,
parameters: ["email": user.email, "password": user.password, "confirmpassword": user.passwordConfirmation],
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
println("register success")
if let succ = successClosure {
succ()
}
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("register fail")
println(error)
if let fail = failureClosure {
fail()
}
})
}
当我收到错误 (BadRequest(ModelState)) 时,我会得到如下输出:
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7f8663e3e890 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f8663e3cba0> { URL: http://192.168.0.71:8888/api/Account/Register } { status code: 400, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 227;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 17 Aug 2014 00:31:57 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
"X-SourceFiles" = "=?UTF-8?B?WjpcUHJvamVjdHNcTGFybnNmaXRcTGFybnNmaXRcYXBpXEFjY291bnRcUmVnaXN0ZXI=?=";
} }, NSLocalizedDescription=Request failed: bad request (400), NSErrorFailingURLKey=http://192.168.0.71:8888/api/Account/Register}
Web API 2 是否没有向我发送 ModelState 无效的原因?还是我错误地访问了错误响应?最终,我想知道 ModelState 无效的原因是什么。
【问题讨论】:
标签: json asp.net-web-api afnetworking asp.net-web-api2 afnetworking-2