最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How can I POST data to a WebAPI controller from Angular's $http service? - Stack Overflow

programmeradmin5浏览0评论

I tried to follow this example.

Here is my C# code:

public class MyModel
{
    int? ID { get; set; }
}

public class MyResourceController : ApiController
{
    [HttpPost]
    public MyModel MyPostAction(MyModel model)
    {
        return model;
    }
}

Here is my 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 plex object?

I tried to follow this example.

Here is my C# code:

public class MyModel
{
    int? ID { get; set; }
}

public class MyResourceController : ApiController
{
    [HttpPost]
    public MyModel MyPostAction(MyModel model)
    {
        return model;
    }
}

Here is my 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 plex object?

Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Aug 6, 2013 at 14:15 Jesus is LordJesus is Lord 15.4k11 gold badges69 silver badges101 bronze badges 1
  • You can skip the stringify by using [FromBody] in the header. see stackoverflow./questions/27869763/… – Peter Kellner Commented Jan 9, 2015 at 23:44
Add a ment  | 

3 Answers 3

Reset to default 8

You don't need to wrap your data into model property:

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

Adding public to the property on MyModel fixed it (facepalm).

I ended up using this on the client:

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

Thanks everyone.

$http.post('/api/MyResource/MyPostAction', data);

Remove the JSON.stringify and post the data as is.

You don't need to specify json header either as it is the default for post.

On the server:

Remove Xml from webapi if you're only using json

//WebApiConfig.js
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
发布评论

评论列表(0)

  1. 暂无评论