【问题标题】:Ajax request throws 500 error, but the request worksAjax 请求抛出 500 错误,但请求有效
【发布时间】:2014-07-15 14:48:17
【问题描述】:

我设置了一个 API 控制器来处理一个 ajax 请求。每次从下面的脚本发出 Ajax 请求时,我都会收到 500 错误:

POST http://localhost:58463/api/Reservations 500 (Internal Server Error) jquery-2.1.0.min.js:4
l.cors.a.crossDomain.send jquery-2.1.0.min.js:4
o.extend.ajax jquery-2.1.0.min.js:4
(anonymous function) Confirm?spaceNumber=5:129
o.event.dispatch jquery-2.1.0.min.js:3
r.handle

但奇怪的是——请求实际上成功了。它创建一个预订。这怎么可能,我该如何解决这个错误?

查看:

@model *********.Models.Reservation
@section Scripts {
   $(document).ready(function () {
        console.log('ready');
        $('#confirmationForm').submit(function (event) {
            event.preventDefault();
            var $form = $(this);
            $.ajax({
                type: $form.prop('method'),
                url: $form.prop('action'),
                data: $form.serialize(),
                dataType: "json",
                traditional: true,
                success: function (response) {
                    console.log('yes!');
                }, 
                error: function(response) {
                    console.log('no');
                }
            });
        });
    });
}

<div class="section about" style="height: 100%;">
    <div id="main-content" class="main-content">
        <div class="container">
            <div class="section-heading">
                <h2 class="red">Confirm Your Reservation</h2><br />
            </div>
            <div class="section-content">
                <div class="row">
                    <div class="hero-buttons text-center">
                        <a href="#" class="btn btn-gray btn-lg white">No</a>
                        <form action="/api/Reservations" method="post" id="confirmationForm">
                            @Html.Hidden("UserName", @Model.UserName)
                            @Html.Hidden("SpaceNumber", @Model.SpaceNumber)
                            <input type="submit" value="Yes" class="btn btn-red btn-lg white">
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

API控制器:

public class ReservationsController : ApiController
{
    private MyContext db = new MyContext();

    // POST api/Reservations
    public HttpResponseMessage PostReservation(Reservation reservation)
    {
        if (ModelState.IsValid)
        {
            reservation.Game = db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID);
            db.Reservations.Add(reservation);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, reservation);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = reservation.ID }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }
}

解决方案

heymega 告诉我进一步查看收到的 500 错误,从而为我指明了正确的方向。使用 FireBug,我在异常消息中发现了这一点:

"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."

我可以通过将这些行添加到我的 WebApiConfig.cs 文件来解决此问题

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

【问题讨论】:

  • 将其置于调试中并单步执行控制器。猜测一下,您在保存预订之后/期间在某处抛出异常,以便实际保存已经发生。如果出现异常,ApiController 将发送 500 响应。
  • @SMcCrohan 我添加了断点 - 看起来响应正在返回状态码 201。还有其他想法吗?
  • @anwyatt 您之前说 HttpStatus 代码是 500,现在是 201...它是什么? 0.o 如果您得到 201,那么这是正确的,因为您正在返回 HttpStatusCode.Created
  • @heymega ajax 请求正在接收 500,但是在添加断点时,我可以看到我的 API 控制器正在返回 201。
  • @anwyatt 好的 - 使用 firebug/fiddler 或任何其他 http 流量查看器查看 500 响应中的数据。在我看来,异常处理程序可能创建了 500 错误,并且您的堆栈跟踪和错误消息将在里面

标签: javascript asp.net ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

您将返回数据类型指定为JSON

 dataType: "json"

jQuery 正在尝试解析对JSON 的响应,但由于无法解析,因此它认为请求不成功。

如果你删除了 dataType,那么 jQuery 会尝试自己解决它,它应该可以解决你的问题。

希望对你有帮助

【讨论】:

  • 删除 dataType: "json" 似乎无法解决问题 - 我应该指定其他数据类型吗?
  • 我注意到的另一件事 - 当我删除 dataType: "json" 时,它在发布表单时不再创建记录。
  • @anwyatt 该数据类型与仅在其响应中发送的请求数据无关,因此它应该仍然创建了您的记录。
  • 啊——实际上你是对的。它仍然会创建记录。
猜你喜欢
  • 2017-06-17
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
相关资源
最近更新 更多