无法将数据传递到asp.net核心 [英] Can't pass data to asp.net core
问题描述
我遇到问题,我需要将数据从Angular发送到ASP.NET Core服务器.这是控制器:
I have a problem, I need to send data from my Angular to my ASP.NET Core server. Here is controller:
[HttpPut]
public IActionResult setCoupon(int id, string CouponCode, int DiscountPercent)
{
try
{
var coupon = new Coupon()
{
Id = id,
CouponCode = CouponCode,
DiscountPercent = DiscountPercent
};
return Ok(coupon);
}
catch (Exception)
{
return BadRequest("Wystąpił błąd");
}
}
这是ngResource的工厂(getCoupon正在工作):
Here is factory from ngResource (getCoupon is working):
app.factory('couponApi',
function($resource) {
return $resource("/coupon/setCoupon",
{},
{
getCoupon: {
method: "GET",
isArray: false
},
putCoupon: {
method: "PUT",
isArray: false,
}
});
});
这是工厂的用法:
$scope.addCouponCode = function(coupon) {
couponApi.putCoupon(coupon);
};
当我调试asp.net服务器时,我发现参数为null或0.我在restangular库上也遇到了同样的问题.
When i debug my asp.net server i found my params null or 0. I have the same problem on restangular library.
我也尝试这种方式来编写控制器方法
I also try this way to write controller method
[HttpPut]
public IActionResult setCoupon(Coupon coupon)
{
try
{
return Ok(coupon);
}
catch (Exception)
{
return BadRequest("Wystąpił błąd");
}
}
我尝试发送的json是这个
My json which I try to send is this
{"id":1,"couponCode":"abc","discountPercent":10}
和我的Echo方法向我发送此信息:
and my Echo method send me this:
{"id":0,"couponCode":null,"discountPercent":0}
更新
显然在asp.net核心中,方法需要具有属性[FromBody]
Apparently in asp.net core, method need to have attribute[FromBody]
[HttpPut]
public IActionResult setCoupon([FromBody] Coupon coupon)
{
try
{
return Ok(coupon);
}
catch (Exception)
{
return BadRequest(new {errorMessage = "Wystąpił błąd"});
}
}
推荐答案
正如奥尔多(Aldo)在评论中所说.答案是C#期望json数据区分大小写.所以:
As Aldo says in the comments. The answer is C# expects case-sensitive matching of the json data. So:
{"id":1,"couponCode":"abc","discountPercent":10}
需要是:
{"id":1,"CouponCode":"abc","DiscountPercent":10}
您为'discountPercent'获得了0,因为这是不匹配的int的默认值,而null是不匹配的字符串的默认值,因此Echo返回:
You were getting a 0 for 'discountPercent' because that is the default value of the unmatched int, whereas null is the default for a unmatched string, hence Echo returns:
{"id":0,"couponCode":null,"discountPercent":0}
这篇关于无法将数据传递到asp.net核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!