Angularjs $ http.post - 将params作为JSON发送到ASPX webmethod

use*_*921 5 javascript c# asp.net webmethod angularjs

我有以下angularjs代码发送http帖子到webmethod,但我得到以下错误没有更多的信息.有人可以帮忙吗?如果我不向webmethod发送任何数据并且只从中获取数据,它就可以了!

无法加载资源:服务器响应状态为500(内部服务器错误)angular.js:11442 POST http:// localhost:54461/GetData.aspx/getData 500(内部服务器错误)

使用Javascript:

var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
$scope.retData = {};

var config = {
    headers: {
        'Content-Type': '"application/json; charset=utf-8";',
        'dataType': '"json"'
    }
}

$scope.retData.getResult = function (item, event) {

    $http.post('GetData.aspx/getData', request, config)
        .success(function (data, status, headers, config) {
            $scope.retData.result = data.d;
        })
        .error(function (data, status, headers, config) {
            $scope.status = status;
        });
}
Run Code Online (Sandbox Code Playgroud)

ASPX webmethod(C#):

public static string getData(string name, int age)
{
    string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}
Run Code Online (Sandbox Code Playgroud)

编辑 --------------------------------------

如果我不向网络方法发送任何json数据,它就可以正常工作.例如下面的代码工作,如果我把断点放在web方法内,它表明它去那里.但如果我发送json数据,它不会进入webmethod:

Javaacript(不发送任何json数据):

var config = {
    headers: {
        'Content-Type': '"application/json; charset=utf-8";',
        'dataType': '"json"'
    }
}

$scope.retData.getResult = function(item, event) {
    $http.post('GetData.aspx/getData', data, config)
        .success(function(data, status, headers, config) {
            $scope.retData.result = data.d;
        })
        .error(function(data, status, headers, config) {
            $scope.status = status;
        });
}
Run Code Online (Sandbox Code Playgroud)

ASPX(没有输入参数时)

public static string getData()
{
    // just having a breakpoint shows it comes inside the 
    // webmethod when no data is passed. 
}
Run Code Online (Sandbox Code Playgroud)

S4b*_*beR 3

您的问题似乎正如 Emmanual Durai 在您的问题的第一条评论中指出的那样:var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";不是有效的 json 对象。

请求会给你{'name':'Nariman'age':'12'}一个字符串,它不会解析为 JSON(格式有问题)。

您应该尝试类似下面的方法来获取有效的字符串

var request = {
    name: "Nariman",
    age: 12
}

var requestString = JSON.stringify(request)
Run Code Online (Sandbox Code Playgroud)

另请查看此处如何将 json POST 数据作为对象传递给 Web API 方法。您的问题通常不是特定于 AngularJS 的,$http而是一般来说是针对XHR请求的。