Can't pass data to asp.net core

↘锁芯ラ 提交于 2019-12-12 04:29:39

问题


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

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

Here is usage of factory:

        $scope.addCouponCode = function(coupon) {
        couponApi.putCoupon(coupon);
    };

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

My json which I try to send is this

{"id":1,"couponCode":"abc","discountPercent":10}

and my Echo method send me this:

{"id":0,"couponCode":null,"discountPercent":0}

Update

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

回答1:


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}

needs to be:

{"id":1,"CouponCode":"abc","DiscountPercent":10}

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}


来源:https://stackoverflow.com/questions/40009668/cant-pass-data-to-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!