【问题标题】:Asp.Net Web API, AngularJS POST RequestAsp.Net Web API,AngularJS POST 请求
【发布时间】:2020-07-06 04:31:54
【问题描述】:

我想发出一个 post 请求并在请求正文中传递一个字符串。 目前有以下控制器 asp.net 和 angularjs 代码。 问题是参数“str”等于null。我做错了什么?

我尝试将 angularjs Content-Type 设置为“application / json”和“text / plain”。 我尝试在 asp.net 中使用和不使用 [FromBody] 选项。 一切都基于 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>

【问题讨论】:

    标签: angularjs asp.net-web-api http-post


    【解决方案1】:

    这段代码是可行的。

        [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;
        }
    

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 2020-03-30
      • 2016-04-10
      • 2014-12-04
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      相关资源
      最近更新 更多