Ajax请求抛出500错误,但请求有效

时间:2014-07-15 14:48:18

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

我设置了一个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>

APIController:

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);

1 个答案:

答案 0 :(得分:0)

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

 dataType: "json"

jQuery正在尝试解析对JSON的响应,因为它不能,它认为请求不成功。

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

希望这有帮助