javascript 如何将数据从 Angular 的 $http 服务发布到 WebAPI 控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18082685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I POST data to a WebAPI controller from Angular's $http service?
提问by Words Like Jared
I tried to follow this example.
我试图遵循这个例子。
Here is my C# code:
这是我的 C# 代码:
public class MyModel
{
int? ID { get; set; }
}
public class MyResourceController : ApiController
{
[HttpPost]
public MyModel MyPostAction(MyModel model)
{
return model;
}
}
Here is my JavaScript:
这是我的 JavaScript:
var data = { model: { ID: 1 } };
$http.post(
'/api/MyResource/MyPostAction',
JSON.stringify(data),
{
headers: {
'Content-Type': 'application/json'
}
}
);
When I set a breakpoint in my action and model.ID
is null
instead of 1
. How can I POST a complex object?
当我在动作设置一个断点,model.ID
是null
不是1
。如何发布一个复杂的对象?
回答by cuongle
You don't need to wrap your data into model
property:
您不需要将数据包装到model
属性中:
var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);
回答by Words Like Jared
Adding public
to the property on MyModel
fixed it (facepalm).
添加public
到MyModel
固定它的属性(facepalm)。
I ended up using this on the client:
我最终在客户端上使用了这个:
var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);
Thanks everyone.
感谢大家。
回答by James Kyburz
$http.post('/api/MyResource/MyPostAction', data);
Remove the JSON.stringify and post the data as is.
删除 JSON.stringify 并按原样发布数据。
You don't need to specify json header either as it is the default for post.
您也不需要指定 json 头,因为它是 post 的默认值。
On the server:
在服务器上:
Remove Xml from webapi if you're only using json
如果您只使用 json,请从 webapi 中删除 Xml
//WebApiConfig.js
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);