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

时间:2013-12-27 12:36:32

标签: asp.net-mvc json jquery asp.net-web-api httpresponse

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

我使用 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#代码),则会触发成功。有什么区别?

由于

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

如果有人还在寻找我的回答。我同意之前的帖子,因为MVC不会返回实际内容。相反,我使用

 public async Task<string> GetAjaxCollateralSummary(string id)
{
//your logic
  return JsonConvert.SerializeObject(result);
}

and the in my js page I have following code:

  $.post(url, { id: '2' })
                    .success(function (response) {
                        console.log(response);
                        var jsondResult = JSON.parse(response);                      
                    }
                        )
                .error(function (err) {
                    console.log("Error while trying to get data from MVC controller  ");
                    console.log(err);
                })