我已经创建了一个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字符串.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。