controller httpresponsemessage好的,但是ajax总是触发fail方法

tra*_*jce 2 asp.net-mvc jquery json httpresponse asp.net-web-api

我遇到了一个奇怪的问题.

我使用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"}
Run Code Online (Sandbox Code Playgroud)

但是,当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 () {
});
Run Code Online (Sandbox Code Playgroud)

这是一个简化的控制器动作:

[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;
}
Run Code Online (Sandbox Code Playgroud)

如果我对web api控制器执行相同的ajax调用(内部使用相同的C#代码),则会触发成功.有什么不同 ?

谢谢

Dar*_*ler 8

您不能将HttpResponseMessage与MVC操作一起使用.Web API和MVC是两个不同的框架,你不能混合和匹配它们的各个部分.