加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax – Angular Xhr发布对Asp.Net Web API请求的结果参数为null

发布时间:2020-12-16 02:51:35 所属栏目:百科 来源:网络整理
导读:我已经创建了一个ASP.Net API控制器,我正在尝试使用Angular发出POST请求.请求到达我的控制器方法,但参数值为null. 我的角色代码: $http({ method: 'POST',url: '/api/Contents',data: "value=foobar",headers: { 'Content-Type': 'application/x-www-form-u
我已经创建了一个ASP.Net API控制器,我正在尝试使用Angular发出POST请求.请求到达我的控制器方法,但参数值为null.

我的角色代码:

$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',data: { "foo": "bar","foo2": "bar2" },headers: { 'Content-Type': 'application/json'} }).
    success(function(data) {
                }).
    error(function(data,config) {

    });

我的(非常简单)Controller方法如下所示:

public void Post([FromBody]string value)
{
    //But Value is NULL!!!!!!
}

以下是我从Chrome中删除的请求标题中的一些值(我认为可能很有趣:

>请求方法:POST
>状态代码:204无内容
>接受:application / json,text / plain,/
>内容类型:application / x-www-form-urlencoded
> X-Requested-With:XMLHttpRequest
>表单Dataview sourceview URL编码
>价值:foobar
>服务器:Microsoft-IIS / 8.0
> X-AspNet-版本:4.0.30319

我错过了什么?

解决方法

像这样:

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

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

});

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

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

或者,您可以使用视图模型:

public class ContentsModel
{
    public string Value { get; set; }
}

然后让控制器操作将视图模型作为参数:

public void Post(ContentsModel model)
{
}

现在您可以发送正常的JSON请求:

$http({ 
    method: 'POST',data: JSON.stringify({ "value": "the value" }),headers: { 'Content-Type': 'application/json' } 
}).success(function(data) {

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

});

另请注意,如果要发送JSON,则需要使用JSON.stringify方法将javascript对象转换为JSON字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读