从Angular 2到ASP.net Core的POST请求不起作用.服务器端的空值

Pio*_*rek 2 c# asp.net angularjs angular

后端,ASP.net核心API:

[Produces("application/json")]
    [Route("api/[controller]")]
    public class StoriesController : Controller
    {
        public static List<Story> STORIES = new List<Story>
            {
                new Story
                {
                    content = "Some really interesting story about dog",
                    timeOfAdding = new DateTime(2016, 8, 26),
                    numberOfViews = 11
                },
                new Story
                {
                    content = "Even cooler story about clown",
                    timeOfAdding = new DateTime(2016, 9, 26),
                    numberOfViews = 11
                },
                new Story
                {
                    content = "And some not cool story",
                    timeOfAdding = new DateTime(2016, 10, 26),
                    numberOfViews = 11
                }
            };

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
            Story story = new Story
            {
                content = value,
                timeOfAdding = DateTime.Now,
                numberOfViews = 0
            };
            STORIES.Add(story);
        }
    }
Run Code Online (Sandbox Code Playgroud)

TypeScript函数:

add(content: string): Observable<Story> {
        let body = JSON.stringify({ "value": content });
        //let body = { "value": content };
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers});

        return this.http.post(this.heroesUrl, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }
Run Code Online (Sandbox Code Playgroud)

发送的参数(在Firefox控制台中看到):

在此输入图像描述

value = null 在Visual Studio 2015调试器中

怎么了?我已经尝试了我在互联网上找到的所有东西:添加/删除标题,删除JSON.stringify,添加/删除[FromBody]属性.结果是每次都一样.

rin*_*usu 7

由于您将值作为JSON传递(如屏幕截图所示),您应该正确使用模型绑定并使用适当的类而不是字符串输入:

public class StoryAddRequest
{
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在控制器中使用它:

// POST api/values
[HttpPost]
public void Post([FromBody] StoryAddRequest request)
{
    if (request != null)
    {
        Story story = new Story
        {
            content = request.Value,
            timeOfAdding = DateTime.Now,
            numberOfViews = 0
        };
        STORIES.Add(story);
    }
}
Run Code Online (Sandbox Code Playgroud)

从文档:

请求数据可以有多种格式,包括JSON,XML和许多其他格式.当您使用该[FromBody]属性指示要将参数绑定到请求正文中的数据时,MVC使用一组已配置的格式化程序来根据其内容类型处理请求数据.默认情况下,MVC包含一个JsonInputFormatter用于处理JSON数据的类,但您可以添加其他格式化程序来处理XML和其他自定义格式.