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

时间:2022-10-16 20:14:13

I setup an API controller to handle an ajax request. Every time the Ajax request is made from the script below I get a 500 error:

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

but the weird thing is - the request actually succeeds. It creates a reservation. How is that possible, and how can I resolve the error?

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

View:

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

Solution

heymega pointed me in the right direction by telling me to look further into the 500 error I was receiving. Using FireBug I found this in the exception message:

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'."

I was able to remedy this by adding these lines to me WebApiConfig.cs file

我能够通过将这些行添加到WebApiConfig.cs文件来解决这个问题

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

1 个解决方案

#1


0  

You are specifying the return data type as JSON

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

 dataType: "json"

jQuery is trying to parse the response to JSON and since it can't, it thinks the request was unsuccessful.

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

If you remove the dataType then jQuery will try and work it out itself and it should fix your issue.

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

Hope this helps

希望这可以帮助

#1


0  

You are specifying the return data type as JSON

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

 dataType: "json"

jQuery is trying to parse the response to JSON and since it can't, it thinks the request was unsuccessful.

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

If you remove the dataType then jQuery will try and work it out itself and it should fix your issue.

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

Hope this helps

希望这可以帮助