ChatGPT解决这个技术问题 Extra ChatGPT

AngularJs $http.post() 不发送数据

谁能告诉我为什么下面的语句没有将帖子数据发送到指定的url?当我打印 $_POST 时,该 url 被调用但在服务器上 - 我得到一个空数组。如果我在将消息添加到数据之前在控制台中打印消息 - 它会显示正确的内容。

$http.post('request-url',  { 'message' : message });

我也尝试过将数据作为字符串(结果相同):

$http.post('request-url',  "message=" + message);

当我以以下格式使用它时,它似乎正在工作:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

但是有没有办法用 $http.post() 来做 - 我是否总是必须包含标题才能让它工作?我相信上述内容类型是指定发送数据的格式,但我可以将它作为 javascript 对象发送吗?

网址是否同源?
抱歉 - 是的,所有示例都是相同的 url
@SpencerMark 抱歉.. 我在您的工作代码上方尝试过.. 它对我不起作用。

F
Felipe Miosso

我在使用 asp.net MVC 和 found the solution here 时遇到了同样的问题

AngularJS 的新手对于为什么 $http 服务速记函数($http.post() 等)似乎不能与 jQuery 等效函数(jQuery.post() 等)交换存在很多困惑。区别在于 jQuery 和 AngularJS 如何序列化和传输数据。从根本上说,问题在于您选择的服务器语言无法原生地理解 AngularJS 的传输……默认情况下,jQuery 使用 Content-Type: x-www-form-urlencoded 和熟悉的 foo=bar&baz=moe 序列化来传输数据。然而,AngularJS 使用 Content-Type: application/json 和 { "foo": "bar", "baz": "moe" } JSON 序列化来传输数据,不幸的是,某些 Web 服务器语言(尤其是 PHP)本身不能反序列化。

奇迹般有效。

代码

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});

我已将此脚本添加到 bower,请使用 bower install angular-post-fix --save-dev 添加它。
那么有没有办法改变php的传输数据方法。因为这是我目前遇到的问题。
这段代码在大多数情况下都很好用,但是在提交空对象的层次结构甚至是扁平的空值时,我遇到了问题。例如 { a: 1, b: { c: { d: { } } }, e: undefined, f: null, g: 2 } 将无法正确编码,PHP 将其作为 [ "a" = >“1”,“g”=>“2”]。 “b”下的整个结构,以及“e”和“f”,包括键本身——都将丢失。我在下面发布了替代代码,上面的结构被解码为: [ "a" => "1", "b" => [ "c" => [ "d" => "" ] ], "e" => "", "f" => "", "g" => "2" ]。
我应该如何为多部分/表单数据实现这个?
精湛:) 确实像一个魅力。我遇到了 Spring MVC 的问题
D
Don F

上面不是很清楚,但是如果您在 PHP 中接收请求,则可以使用:

$params = json_decode(file_get_contents('php://input'),true);

从 AngularJS POST 访问 PHP 中的数组。


当用它覆盖 $_POST 数组时,我需要添加 true 以强制它到数组中。 json_decode(file_get_contents('php://input'), true);
@Zalaboza,我同意很难将任何解决方案视为“通用”,但我不同意它是“hacky”--- php.net 声明:“file_get_contents() 是阅读内容的首选方式将文件转换为字符串。如果您的操作系统支持,它将使用内存映射技术来提高性能。当然,在这种情况下我们没有读取文件,但我们仍然在读取发布的 json 数据。如果您能提供新的答案或提供新的信息来帮助读者(包括我自己)对此做出更好的决定,那就太好了。
j
jonprasetyo

您可以像这样设置默认的“Content-Type”:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

关于 data 格式:

$http.post 和 $http.put 方法接受任何 JavaScript 对象(或字符串)值作为它们的数据参数。如果 data 是 JavaScript 对象,默认情况下,它将被转换为 JSON 字符串。

尝试使用这种变体

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

它似乎不起作用。我刚刚尝试了将数据作为字符串和 : headers: {'Content-Type': 'application/x-www-form-urlencoded'} 的变体 - 这似乎有效,但有没有更好的方法它?
如上所述设置默认内容类型,并且对于数据不要使用 js 对象。使用这样的字符串:'message='+message 对我有用
C
Community

我遇到了类似的问题,我想知道这是否也有用:https://stackoverflow.com/a/11443066

var xsrf = $.param({fkey: "key"});
$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

问候,


看起来标题是我们需要的唯一更改。谢谢!
谢谢,这对我有用:) 问题是 POST 数据的编码。
R
Rômulo Collopy

我喜欢使用函数将对象转换为 post 参数。

myobject = {'one':'1','two':'2','three':'3'}

Object.toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
        p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
};

$http({
    method: 'POST',
    url: url,
    data: Object.toparams(myobject),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

S
Stetzon

这终于在 Angular 1.4 中使用 $httpParamSerializerJQLike 解决了

请参阅https://github.com/angular/angular.js/issues/6039

.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
  method: 'POST',
  url: baseUrl,
  data: $httpParamSerializerJQLike({
    "user":{
      "email":"wahxxx@gmail.com",
      "password":"123456"
    }
  }),
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
})})

我面临问题 POST 192.168.225.75:7788/procure/p/search 400(错误请求)
M
Madan Sapkota

我将 jQuery paramAngularJS post 请求一起使用。这是一个示例... 创建 AngularJS 应用程序模块,其中 myapp 在您的 HTML 代码中使用 ng-app 定义。

var app = angular.module('myapp', []);

现在让我们创建一个登录控制器并 POST 电子邮件和密码。

app.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
    // default post header
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    // send login data
    $http({
        method: 'POST',
        url: 'https://example.com/user/login',
        data: $.param({
            email: $scope.email,
            password: $scope.password
        }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {
        // handle success things
    }).error(function (data, status, headers, config) {
        // handle error things
    });
}]);

我不喜欢解释代码,它很容易理解:) 请注意,param 来自 jQuery,因此您必须同时安装 jQuery 和 AngularJS 才能使其正常工作。这是一个屏幕截图。

https://i.stack.imgur.com/STv5A.png

希望这会有所帮助。谢谢!


a
alknows

我对 AngularJS 和 Node.js + Express 4 + 路由器有同样的问题

路由器期望来自 post 请求的数据在正文中。如果我遵循 Angular Docs 中的示例,此正文始终为空

符号 1

$http.post('/someUrl', {msg:'hello word!'})

但是如果我在数据中使用它

符号 2

$http({
       withCredentials: false,
       method: 'post',
       url: yourUrl,
       headers: {'Content-Type': 'application/x-www-form-urlencoded'},
       data: postData
 });

编辑1:

否则,如果使用符号 1,node.js 路由器将期望 req.body 中的数据:

req.body.msg

它还将信息作为 JSON 有效负载发送。在某些情况下,这会更好,因为您的 json 中有数组并且 x-www-form-urlencoded 会产生一些问题。

有效。希望能帮助到你。


R
Roman

与 JQuery 不同,为了迂腐,Angular 使用 JSON 格式从客户端到服务器的 POST 数据传输(JQuery 大概应用 x-www-form-urlencoded,尽管 JQuery 和 Angular 使用 JSON 进行数据输入)。因此有两个部分的问题:在 js 客户端部分和您的服务器部分。所以你需要:

像这样放置 js Angular 客户端部分: $http({ method: 'POST', url: 'request-url', data: {'message': 'Hello world'} });

在您的服务器部分写入以接收来自客户端的数据(如果它是 php)。 $data = file_get_contents("php://input"); $dataJsonDecode = json_decode($data); $message = $dataJsonDecode->message;回显$消息; //'你好世界'

注意:$_POST 不起作用!

该解决方案对我来说很好,希望对你有用。


R
Renaud

以@felipe-miosso 的回答为基础:

从这里下载它作为一个 AngularJS 模块,安装它把它添加到你的应用程序中: var app = angular.module('my_app', [ ... , 'httpPostFix']);


B
BERGUIGA Mohamed Amine

要使用 angularjs 的 $http 通过 Post 方法发送数据,您需要更改

data: "message=" + message,与 data: $.param({message:message})


为什么在发送 AngularJS 发布数据时需要 data: $.param ?
E
Esten

我没有评论的声誉,但作为对唐 F 的回应/补充:

$params = json_decode(file_get_contents('php://input'));

true 的第二个参数需要添加到 json_decode 函数才能正确返回关联数组:

$params = json_decode(file_get_contents('php://input'), true);


M
Malcolm Swaine

  var payload = $.param({ jobId: 2 });

                this.$http({
                    method: 'POST',
                    url: 'web/api/ResourceAction/processfile',
                    data: payload,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

网络API 2

public class AcceptJobParams
        {
            public int jobId { get; set; }
        }

        public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
        {
            // do something with fileName parameter

            return Ok();
        }

S
Spartak Lalaj

这段代码为我解决了这个问题。它是一个应用级解决方案:

moduleName.config(['$httpProvider',
  function($httpProvider) {
    $httpProvider.defaults.transformRequest.push(function(data) {
        var requestStr;
        if (data) {
            data = JSON.parse(data);
            for (var key in data) {
                if (requestStr) {
                    requestStr += "&" + key + "=" + data[key];
                } else {
                    requestStr = key + "=" + data[key];
                }
            }
        }
        return requestStr;
    });
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  }
]);

D
Dor Cohen

将此添加到您的 js 文件中:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

并将其添加到您的服务器文件中:

$params = json_decode(file_get_contents('php://input'), true);

那应该行得通。


V
Viraj

我也面临类似的问题,我正在做这样的事情,但没有奏效。我的 Spring 控制器无法读取数据参数。

var paramsVal={data:'"id":"1"'};
  $http.post("Request URL",  {params: paramsVal});  

但是阅读这个论坛和 API Doc,我尝试了以下方式,这对我有用。如果有人也有类似的问题,您也可以尝试以下方法。

$http({
      method: 'POST',
      url: "Request URL",           
      params: paramsVal,
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
            });

请检查 https://docs.angularjs.org/api/ng/service/$http#post 以了解 param config 的作用。 {data:'"id":"1"'} – 将转换为 URL?data="id:1" 的字符串或对象的映射


o
oneLeggedChicken

这可能是一个迟到的答案,但我认为最合适的方法是在使用您 $httpParamSerializer 进行“获取”请求时使用相同的代码角度使用将不得不将其注入您的控制器,这样您就可以简单地执行以下操作根本不必使用 Jquery,$http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
    $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

b
bArraxas

就我而言,我解决了这样的问题:

var deferred = $q.defer();

$http({
    method: 'POST',
    url: 'myUri', 
    data: $.param({ param1: 'blablabla', param2: JSON.stringify(objJSON) }),
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(
    function(res) {
        console.log('succes !', res.data);
        deferred.resolve(res.data);
    },
    function(err) {
        console.log('error...', err);
        deferred.resolve(err);
    }
);
return deferred.promise;

您需要对包含 JSON 对象的每个参数使用 JSON.stringify,然后使用“$.param”构建您的数据对象 :-)

注意:我的“objJSON”是一个 JSON 对象,包含数组、整数、字符串和 html 内容。他的总大小超过 3500 个字符。


N
Nis

我知道已经接受了答案。但是,如果答案出于任何原因不适合他们,以下内容可能对未来的读者有所帮助。

Angular 不像 jQuery 那样做 ajax。当我尝试按照指南修改 angular $httpprovider 时,我遇到了其他问题。例如,我使用其中 $this->input->is_ajax_request() 函数总是失败的 codeigniter(由另一个程序员编写并在全局范围内使用,因此无法更改)说这不是真正的 ajax 请求。

为了解决这个问题,我求助于 deferred promise。我在 Firefox 和 ie9 中对其进行了测试,并且可以正常工作。

我在任何角度代码之外定义了以下函数。此函数进行常规 jquery ajax 调用并返回延迟/承诺(我仍在学习)对象。

function getjQueryAjax(url, obj){
    return $.ajax({
        type: 'post',
        url: url,
        cache: true,
        data: obj
    });
}

然后我使用以下代码将其称为角度代码。请注意,我们必须使用 $scope.$apply() 手动更新 $scope

    var data = {
        media: "video",
        scope: "movies"
    };
    var rPromise = getjQueryAjax("myController/getMeTypes" , data);
    rPromise.success(function(response){
        console.log(response);
        $scope.$apply(function(){
            $scope.testData = JSON.parse(response);
            console.log($scope.testData);
        });
    }).error(function(){
        console.log("AJAX failed!");
    });

这可能不是完美的答案,但它允许我使用 angular 的 jquery ajax 调用并允许我更新 $scope


从 1.3 开始,Angular 有自己的 Promise 服务,称为 $q。无需使用 JQuery 发布帖子。
M
Muhammad Soliman

我在 express 中遇到了同样的问题 .. 要解决您必须在发送 http 请求之前使用 bodyparser 解析 json 对象..

app.use(bodyParser.json());

M
Mahdi Rostami

我正在使用带有 angular js 的 asp.net WCF webservices 并且下面的代码有效:

 $http({
        contentType: "application/json; charset=utf-8",//required
        method: "POST",
        url: '../../operation/Service.svc/user_forget',
        dataType: "json",//optional
        data:{ "uid_or_phone": $scope.forgettel, "user_email": $scope.forgetemail },
        async: "isAsync"//optional

       }).success( function (response) {

         $scope.userforgeterror = response.d;                    
       })

希望能帮助到你。


S
Sheo Narayan

没有找到完整的代码片段,说明如何使用 $http.post 方法将数据发送到服务器以及为什么它在这种情况下不起作用。

以下代码片段的解释...

我正在使用 jQuery $.param 函数将 JSON 数据序列化为 www post 数据 在配置变量中设置 Content-Type,该变量将与 angularJS $http.post 的请求一起传递,指示服务器我们正在发送数据www 帖子格式。注意 $htttp.post 方法,其中我将第一个参数作为 url 发送,第二个参数作为数据(序列化)发送,第三个参数作为配置发送。

剩下的代码是自己理解的。

$scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

查看 $http.post method here 的代码示例。


L
Luis Felipe Barnett V

如果您使用 PHP,这是一种从 AngularJS POST 访问 PHP 数组的简单方法。

$params = json_decode(file_get_contents('php://input'),true);

S
Saeb Amini

如果使用 Angular >= 1.4,这是使用 the serializer provided by Angular 的最简洁的解决方案:

angular.module('yourModule')
  .config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
    $httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});

然后您可以在应用程序的任何位置简单地执行此操作:

$http({
  method: 'POST',
  url: '/requesturl',
  data: {
    param1: 'value1',
    param2: 'value2'
  }
});

并且它将正确地将数据序列化为 param1=value1&param2=value2 并将其发送到 /requesturl 并带有 application/x-www-form-urlencoded; charset=utf-8 Content-Type 标头,正如端点上的 POST 请求通常所期望的那样。

TL;博士

在我的研究中,我发现这个问题的答案有很多种。有些非常复杂并且依赖于自定义函数,有些依赖于 jQuery,有些则不完整,建议您只需要设置标题。

如果您只设置 Content-Type 标头,端点将看到 POST 数据,但它不会采用标准格式,因为除非您提供一个字符串作为您的 data,或者手动序列化您的数据对象,否则它将所有默认情况下都被序列化为 JSON,并且可能在端点被错误地解释。

例如,如果在上面的示例中没有设置正确的序列化程序,它将在端点中被视为:

{"param1":"value1","param2":"value2"}

这可能导致意外的解析,例如 ASP.NET 将其视为 null 参数名称,将 {"param1":"value1","param2":"value2"} 视为值;或者 Fiddler 以另一种方式解释它,将 {"param1":"value1","param2":"value2"} 作为参数名称,将 null 作为值。


B
Benjamin Intal

类似于 OP 建议的工作格式 &丹尼森的回答,除了使用 $http.post 而不仅仅是 $http 并且仍然依赖于 jQuery。

在这里使用 jQuery 的好处是可以正确传递复杂的对象;反对手动转换为可能导致数据乱码的 URL 参数。

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

J
JeanValjean

只需将您要发送的数据作为第二个参数:

$http.post('request-url',  message);

另一种也有效的形式是:

$http.post('request-url',  { params: { paramName: value } });

确保 paramName 与您正在调用的函数的参数名称完全匹配。

来源:AngularJS post shortcut method


谁能解释为什么这个答案被否决了?
这个解决方案不可能被否决,它是最简单、最短且在 Angular 文档中得到证明的docs.angularjs.org/api/ng/service/$http
D
D. Kermott

当我遇到这个问题时,我发布的参数原来是一个对象数组而不是一个简单的对象。


K
Kevin Brown-Silva

刚从angular 1.2更新到1.3,发现代码有问题。转换资源将导致无限循环,因为(我认为) $promise 再次持有同一个对象。也许它会帮助某人......

我可以通过以下方式解决这个问题:

[...]
  /**
 * The workhorse; converts an object to x-www-form-urlencoded serialization.
 * @param {Object} obj
 * @return {String}
 */
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

angular.forEach(obj, function(value, name) {
+    if(name.indexOf("$promise") != -1) {
+        return;
+    }

    value = obj[name];
    if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
[...]

o
obe

我一直在使用公认答案的代码(Felipe 的代码)一段时间,并且效果很好(感谢 Felipe!)。

但是,最近我发现它存在空对象或数组的问题。例如,提交此对象时:

{
    A: 1,
    B: {
        a: [ ],
    },
    C: [ ],
    D: "2"
}

PHP 似乎根本看不到 B 和 C。它得到这个:

[
    "A" => "1",
    "B" => "2"
]

查看 Chrome 中的实际请求可以看出:

A: 1
:
D: 2

我写了一个替代代码片段。它似乎适用于我的用例,但我尚未对其进行广泛测试,因此请谨慎使用。

我使用 TypeScript 是因为我喜欢强类型,但它很容易转换为纯 JS:

angular.module("MyModule").config([ "$httpProvider", function($httpProvider: ng.IHttpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

    function phpize(obj: Object | any[], depth: number = 1): string[] {
        var arr: string[] = [ ];
        angular.forEach(obj, (value: any, key: string) => {
            if (angular.isObject(value) || angular.isArray(value)) {
                var arrInner: string[] = phpize(value, depth + 1);
                var tmpKey: string;
                var encodedKey = encodeURIComponent(key);
                if (depth == 1) tmpKey = encodedKey;
                else tmpKey = `[${encodedKey}]`;
                if (arrInner.length == 0) {
                    arr.push(`${tmpKey}=`);
                }
                else {
                    arr = arr.concat(arrInner.map(inner => `${tmpKey}${inner}`));
                }
            }
            else {
                var encodedKey = encodeURIComponent(key);
                var encodedValue;
                if (angular.isUndefined(value) || value === null) encodedValue = "";
                else encodedValue = encodeURIComponent(value);

                if (depth == 1) {
                    arr.push(`${encodedKey}=${encodedValue}`);
                }
                else {
                    arr.push(`[${encodedKey}]=${encodedValue}`);
                }
            }
        });
        return arr;
    }

    // Override $http service's default transformRequest
    (<any>$httpProvider.defaults).transformRequest = [ function(data: any) {
        if (!angular.isObject(data) || data.toString() == "[object File]") return data;
        return phpize(data).join("&");
    } ];
} ]);

它比 Felipe 的代码效率低,但我认为这并不重要,因为与 HTTP 请求本身的总体开销相比,它应该是即时的。

现在 PHP 显示:

[
    "A" => "1",
    "B" => [
        "a" => ""
    ],
    "C" => "",
    "D" => "2"
]

据我所知,不可能让 PHP 识别 Ba 和 C 是空数组,但至少出现了键,这在存在依赖于某个结构的代码时很重要,即使它内部基本上是空的。

另请注意,它将未定义和空值转换为空字符串。


TypeScript 是使用 JavaScript 在 POO 中编码的最佳方式!
p
pixparker

我通过以下代码解决了这个问题:

客户端(Js):

     $http({
                url: me.serverPath,
                method: 'POST',
                data: data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            }).
                success(function (serverData) {
                    console.log("ServerData:", serverData);
    ......

注意 data 是一个对象。

在服务器上(ASP.NET MVC):

[AllowCrossSiteJson]
        public string Api()
        {
            var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
            if (data == null) return "Null Request";
            var bl = Page.Bl = new Core(this);

            return data.methodName;
        }

跨域请求需要“AllowCrossSiteJsonAttribute”:

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }

希望这很有用。