POST request from Angular 2 to ASP.net Core doesn&

2020-03-26 08:49发布

问题:

Backend, ASP.net Core 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);
        }
    }

TypeScript function:

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);
    }

Parameters sent (seen in Firefox console):

value = null in Visual Studio 2015 debugger

What's wrong? I've tried everything that I found in internet: adding/removing headers, removing JSON.stringify, adding/removing [FromBody] attribute. Result is every time the same.

回答1:

Since you're passing your value as JSON (as the screenshot suggests), you should use the model binding correctly and use a proper class instead of a string input:

public class StoryAddRequest
{
    public string Value { get; set; }
}

You then can use it in your controller:

// 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);
    }
}

From the documentation:

Request data can come in a variety of formats including JSON, XML and many others. When you use the [FromBody] attribute to indicate that you want to bind a parameter to data in the request body, MVC uses a configured set of formatters to handle the request data based on its content type. By default MVC includes a JsonInputFormatter class for handling JSON data, but you can add additional formatters for handling XML and other custom formats.