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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:40:50  来源:igfitidea点击:

How can I POST data to a WebAPI controller from Angular's $http service?

c#javascriptangularjsasp.net-web-api

提问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.IDis nullinstead of 1. How can I POST a complex object?

当我在动作设置一个断点,model.IDnull不是1。如何发布一个复杂的对象?

回答by cuongle

You don't need to wrap your data into modelproperty:

您不需要将数据包装到model属性中:

var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);

回答by Words Like Jared

Adding publicto the property on MyModelfixed it (facepalm).

添加publicMyModel固定它的属性(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);