由于语法无效(ASP.NET),服务器无法处理PUT请求

时间:2018-07-19 10:24:09

标签: javascript c# .net ajax api

我正在尝试使用ajax发出PUT请求以更新Rental对象。这是ajax请求。请注意,img.attr("data-rental-id")可以正常工作。

$("#rentals").on("click", ".js-update", function () {
                    var img = $(this);
                    var vm = {};
                    vm.id = parseInt(img.attr("data-rental-id"));
                    vm.dateReturned = new Date(); 
                    bootbox.confirm("Are you sure you want to mark this rental as returned?", function (result) {
                        if (result) {
                            $.ajax({
                                url: "/api/newRentals/" + img.attr("data-rental-id"),
                                type: "PUT",
                                data: vm,
                                success: function () {
                                    alert('Updated');
                                }
                            });
                        }
                    });
                });

这是我的API更新方法:

[HttpPut]
public IHttpActionResult UpdateRental(UpdatedRentalDto UpdatedRentalDto)
{
    if (!ModelState.IsValid)
        return BadRequest();

    var rentalInDb = _context.Rentals.SingleOrDefault(r => r.Id == UpdatedRentalDto.Id);

    if (rentalInDb == null)
        return NotFound();

    Mapper.Map(UpdatedRentalDto, rentalInDb);

    _context.SaveChanges();

    return Ok();
}

最后是我的DTO:

public class UpdatedRentalDto
{
    [Required]
    public int Id { get; set; }

    public DateTime DateReturned { get; set; }
}

从理论上讲,一切似乎都很好,但是,当我尝试运行它时,我得到了:

HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
(XHR)PUT - http://localhost:57265/api/newRentals/1

这是否意味着数据变量vm有问题?怎么了?

1 个答案:

答案 0 :(得分:1)

我认为您的问题出在javascrip的日期时间格式-/ C#。如果您使用JavaScript执行新日期,则会收到(在我的浏览器版本中:Thu Jul 19 2018 12:31:40 GMT + 0200(Romance Daylight Time)。您将其发送到服务器,可能无法解析为DateTime C#的字段。

1)将对NewtonSoft.Json的引用添加到您的c#项目中

2)添加一个DateFormatConverter类,这是我的示例

public class DateFormatConverter : IsoDateTimeConverter
    {
        public DateFormatConverter(string format)
        {
            DateTimeFormat = format;
            Culture = new CultureInfo("nl-BE"); //use this to have CET time !
        }
    }

2)在dto中,可以使用此属性在其中定义(使用所需的日期时间格式)

[JsonConverter(typeof(DateFormatConverter), "dd/MM/yyyy HH:mm")]

3)在javascript中添加对moment.js(非常流行的日期/时间处理库)的引用

4)在发送到服务器之前,使用momentJS的格式化功能格式化日期时间

相关问题