Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

angularjs - Can't pass data to 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");
    }
}

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"});
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...