string value is Empty when using FromBody in asp.net web api

后端 未结 2 1669
予麋鹿
予麋鹿 2020-12-20 01:19

I am using asp.net core web api. below is my simple post function which is having a single string parameter. The problem is when I use [FromBody] the string stays null. I am

相关标签:
2条回答
  • 2020-12-20 01:51

    Like the doc says :

    When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter.

    Only XML and JSON content-types are supported by default. So you need to use application/xml, application/json or register a custom IInputFormatter.

    Next, you need to send a content that match the selected content-type. For json, if the parameter is int send a number. If it's a class, send a json object. If it's a string, send a json string. Etc.

    int => 14
    string => "azerty"
    class => { "propName" : "value" }
    Array => []
    ... => ...
    

    In your case you should send application/json content-type and as content :

    "Hello string"
    

    And not just

    Hello string
    

    Aspnet core json input formatter implementation

    Aspnet core xml input formatter implementation

    Example: Creating a CSV Media Formatter

    0 讨论(0)
  • 2020-12-20 01:58

    I did make it work by passing as row data in PostMan. Do not forget to add "=" sign as prefix in to the values.

     public string Post([FromBody]string value)
     {
         return value;
     }
    

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