当使用contentType:'application/json; charset=utf-8'时,我的数据没有传递到API控制器

4

我正在使用web api中的PUT更新记录,当我使用contentType: 'application/json; charset=utf-8'时,我的数据未传递到api控制器,但是当我注释此行时,数据被传输。有没有人能解释一下?以下是来自mvc视图的调用:

$(function () {
        $("#btnSubmit").click(function () {
            var id = $("#hdnProductID").val();
            var ProductName = $("#txtProductName").val();
            var QuantityPerUnit = $("#txtQuantityPerUnit").val();
            var ReorderLevel = $("#txtReorderLevel").val();
            var UnitPrice = $("#txtUnitPrice").val();
            var UnitsInStock = $("#txtUnitsInStock").val();
            var UnitsOnOrder = $("#txtUnitsOnOrder").val();

            $.ajax({
                url: "http://localhost:2821/api/Products"+ "/" + id,
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data:{ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder},
                success: function (data) {
                    alert("success");
                },
                error: function (msg) {
                    alert(msg);
                }

            });
        });
    });

以下是我的控制器方法
public IHttpActionResult PutProduct(int id, Product product)
 {}

尝试使用data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}) - T J
@Muzammil contentType: 'application/json; charset=utf-8', 是有效的吗?你尝试过只使用 contentType: 'application/json;' 吗?参考这个链接:https://dev59.com/cXRB5IYBdhLWcg3w4bKv - zer00ne
1
@zer00ne 不需要使用charset,因为使用ajax请求时唯一有效的是utf-8,但这应该不是问题。问题在于OP告诉服务器发送JSON数据,但OP在data中没有传递任何JSON格式的数据。 - t.niese
1个回答

2
如果请求中未指定contentType,则采用默认的contentType,即"application/x-www-form-urlencoded; charset=UTF-8",不需要将post数据转换为字符串。但是,如果contentType是"application/json; charset=utf-8",则需要显式地将post数据转换为字符串。因此应该这样做:
    $.ajax({
            url: "http://localhost:2821/api/Products"+ "/" + id,
            type: 'PUT',
            contentType: 'application/json; charset=utf-8',
            data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}),
            success: function (data) {
                alert("success");
            },
            error: function (msg) {
                alert(msg);
            }

        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接