我正在尝试处理正在构建的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无效的原因是什么。
在AFNetworking中,可以通过以下方式访问Web API 2提供的错误: operation.responseString
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句