gpt4 book ai didi

ajax - 对 Asp.Net Web API 的 Angular Xhr 发布请求导致参数为空

转载 作者:行者123 更新时间:2023-12-05 00:30:22 24 4
gpt4 key购买 nike

我已经创建了一个 ASP.Net API Controller ,我正在尝试使用 Angular 向它发出 POST 请求。请求到达我的 Controller 方法,但参数值为空。

我的 Angular 代码:

$http({ method: 'POST', url: '/api/Contents', data: "value=foobar", headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).
success(function(data) {
}).
error(function(data, status, headers, config) {

});

我也试过用json(我最终想要的是json):
$http({ method: 'POST', url: '/api/Contents', data: { "foo": "bar", "foo2": "bar2" }, headers: { 'Content-Type': 'application/json'} }).
success(function(data) {
}).
error(function(data, status, headers, config) {

});

我的(非常简单的)Controller 方法如下所示:
public void Post([FromBody]string value)
{
//But Value is NULL!!!!!!
}

以下是我从 Chrome 中截取的请求 header 中的一些值(我认为可能很有趣的那些值:
  • 请求方式:POST
  • 状态码:204 无内容
  • 接受:application/json、text/plain、/
  • 内容类型:应用程序/x-www-form-urlencoded
  • X-Requested-With: XMLHttpRequest
  • 表单数据 View 源 View URL 编码
  • 值:foobar
  • 服务器:Microsoft-IIS/8.0
  • X-AspNet 版本:4.0.30319

  • 我错过了什么?

    最佳答案

    像这样:

    $http({ 
    method: 'POST',
    url: '/api/Contents',
    data: "=foobar",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).success(function(data) {

    }).error(function(data, status, headers, config) {

    });

    请注意 =foobar数据参数。在这种情况下,您不应指定参数名称。是的,我知道,别问了。

    您可以阅读更多关于 how model binding in the Web API works .如果你像我一样发现这绝对是疯了,你可以考虑使用 ServiceStack 反而。

    或者,您可以使用 View 模型:
    public class ContentsModel
    {
    public string Value { get; set; }
    }

    然后让您的 Controller 操作将 View 模型作为参数:
    public void Post(ContentsModel model)
    {
    }

    现在你可以发送一个普通的 JSON 请求:
    $http({ 
    method: 'POST',
    url: '/api/Contents',
    data: JSON.stringify({ "value": "the value" }),
    headers: { 'Content-Type': 'application/json' }
    }).success(function(data) {

    }).error(function(data, status, headers, config) {

    });

    还要注意如果你想发送 JSON 你需要使用 JSON.stringify将 javascript 对象转换为 JSON 字符串的方法。

    关于ajax - 对 Asp.Net Web API 的 Angular Xhr 发布请求导致参数为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16151566/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com