POST request from Angular 2 to ASP.net Core doesn't work. Null value on server side

前端 未结 1 942
走了就别回头了
走了就别回头了 2021-01-15 02:20

Backend, ASP.net Core API:

[Produces(\"application/json\")]
    [Route(\"api/[controller]\")]
    public class StoriesController : Controller
    {
        p         


        
相关标签:
1条回答
  • 2021-01-15 02:38

    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.

    0 讨论(0)
提交回复
热议问题