0
votes

I want to make a post request and pass a string in the request body. At the moment there is the following controller asp.net and angularjs code. The problem is that the parameter "str" comes equal to null. What am I doing wrong?

I tried to set angularjs Content-Type as "application / json" and as "text / plain". I tried in asp.net with and without [FromBody] option. Everything is based on NET.Framework 4.6.2

[Route("sections/add")]
    [HttpPost]
    public HttpResponseMessage AddSection([FromBody]string str)
    {
        var response = this.Request.CreateResponse();

        str = str + " 1";

        response.Content = new StringContent(str, Encoding.UTF8, "application/json");
        return response;
    }

var calcsApp = angular.module('calcsCatApp', []);

calcsApp.controller('editController', ['$scope', '$rootScope', '$http', '$httpParamSerializerJQLike', function ($scope, $rootScope, $http, 
$httpParamSerializerJQLike) { 

    $scope.addSection = function (sectionToAdd) {
        let url = 'api/sections/add';
        let jData = { str: "Section1" };
        $http({
            method: 'POST',
            url: url,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            data: $httpParamSerializerJQLike(jData)
        })
        .then(function (response) {
            alert('response OK: ' + response.data);
        }, function (response) {
            alert('response error: ' + response.data);
        });
    };

}]);
<!DOCTYPE html>
<html ng-app="calcsCatApp">
<head>
    <meta charset="UTF-8">
</head>
<body>
<div ng-controller="editController">
<input type="button" value="+" ng-click="addSection()"/>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js">
</script>
</body>
</html>
1

1 Answers

0
votes

This code is workable.

    [Route("sections/add")]
    [HttpPost]
    public HttpResponseMessage AddSection()
    {
        HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK);
        string bodyString = Request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        response.Content = new StringContent(bodyString, Encoding.UTF8, "application/json");
        return response;
    }