【发布时间】:2014-01-15 01:18:42
【问题描述】:
我遇到了一个奇怪的问题。
我使用 MVC(不是 web api),所以控制器继承自 Controller,而不是 ApiController。
我正在使用 ajax 调用控制器操作 (POST),并且该操作正在返回 HttpResponseMessage
这是我得到的回应:
{"readyState":4,"responseText":"StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:\r\n{\r\n Location: /\r\n Content-Type: application/json; charset=utf-8\r\n}","status":200,"statusText":"OK"}
但是,当 ajax 接收到数据时,它会触发 fail 方法。
这是ajax函数:
$.ajax({
url: "someurl",
type: "post",
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8"
}).done(function (data) {
alert(data.responseText);
window.location.href = "redirect to some url";
}).fail(function (data) {
alert("error");<-- this one is called even when i set HttpStatusCode.OK
alert(JSON.stringify(data));
}).always(function () {
});
这是一个简化的控制器动作:
[HttpPost]
[AllowAnonymous]
public HttpResponseMessage Index(HttpRequestMessage request, Login model)
//public HttpResponseMessage Index(Login model) // i get the same with any of these 2
{
HttpResponseMessage response = new HttpResponseMessage();
string message = "";
if (something)
{
response.StatusCode = HttpStatusCode.OK;
FormsAuthentication.SetAuthCookie(model.UserName, true);
currentUser.LastLoginDate = DateTime.Now;
currentUser.FailedPasswordAttemptCount = 0;
ModelRepositories.MobileCommerceRepository.SaveChanges();
}
else
{
message = "User does not exist. The user name or password provided is incorrect.";
response.StatusCode = HttpStatusCode.BadRequest;
}
//response = request.CreateResponse(HttpStatusCode.OK);
string json = JsonSerializer.SerializeToString(message);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;
}
如果我改为对 web api 控制器执行相同的 ajax 调用(内部使用相同的 C# 代码),它会触发成功。有什么区别?
谢谢
【问题讨论】:
标签: asp.net-mvc json jquery asp.net-web-api httpresponse