【问题标题】:controller httpresponsemessage OK, but ajax always fires the fail method控制器 httpresponsemessage OK,但 ajax 总是触发失败方法
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 还有其他选择吗?如果您的应用程序无法添加任何 Web api 控制器并且仅限于普通的 MVC 控制器怎么办?
    • @ncbl 要在 MVC 中写出正文,您可以使用 context.Response.Write(...)
    • 我认为这不再适用于 .net 核心,因为 MVC 和 WebAPI 结合在一起
    【解决方案2】:

    如果有人还在寻找,请提出我的答案。我同意之前的帖子,因为 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);
                    })
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2013-11-15
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      相关资源
      最近更新 更多