FromBody string parameter is giving null












20















This is probably something very basic, but I am having trouble figuring out where I am going wrong.



I am trying to grab a string from the body of a POST, but "jsonString" only shows as null. I also want to avoid using a model, but maybe this isn't possible. The piece of code that I am hitting with PostMan is this chunk:



[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
...
}


Maybe it is something I am doing incorrectly with postman, but I have been trying to use "=test" (as seen in other questions asked about this topic) in the value section of the body - x-www-form-urlencoded section with the key as jsonString and nothing. I have also tried using raw - text and raw - text/plain. I get the id so I know the url is correct. Any help with this would be greatly appreciated.



PostMan is set up like this currently:



POST http://localhost:8000/Edit/Test?id=111
key = id value = 111
Body - x-www-form-urlencoded
key = jsonString value = "=test"









share|improve this question

























  • Can you please provide your full http request including URL & body in your question.

    – matthensley.io
    Nov 28 '16 at 20:57













  • At least Request.Content.ReadAsStringAsync() should work.

    – Fabio
    Nov 28 '16 at 21:01






  • 1





    I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

    – Igor
    Nov 28 '16 at 21:23











  • Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

    – Michael Freidgeim
    Nov 18 '17 at 1:18











  • I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

    – Gineer
    Jun 7 '18 at 13:49
















20















This is probably something very basic, but I am having trouble figuring out where I am going wrong.



I am trying to grab a string from the body of a POST, but "jsonString" only shows as null. I also want to avoid using a model, but maybe this isn't possible. The piece of code that I am hitting with PostMan is this chunk:



[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
...
}


Maybe it is something I am doing incorrectly with postman, but I have been trying to use "=test" (as seen in other questions asked about this topic) in the value section of the body - x-www-form-urlencoded section with the key as jsonString and nothing. I have also tried using raw - text and raw - text/plain. I get the id so I know the url is correct. Any help with this would be greatly appreciated.



PostMan is set up like this currently:



POST http://localhost:8000/Edit/Test?id=111
key = id value = 111
Body - x-www-form-urlencoded
key = jsonString value = "=test"









share|improve this question

























  • Can you please provide your full http request including URL & body in your question.

    – matthensley.io
    Nov 28 '16 at 20:57













  • At least Request.Content.ReadAsStringAsync() should work.

    – Fabio
    Nov 28 '16 at 21:01






  • 1





    I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

    – Igor
    Nov 28 '16 at 21:23











  • Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

    – Michael Freidgeim
    Nov 18 '17 at 1:18











  • I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

    – Gineer
    Jun 7 '18 at 13:49














20












20








20


1






This is probably something very basic, but I am having trouble figuring out where I am going wrong.



I am trying to grab a string from the body of a POST, but "jsonString" only shows as null. I also want to avoid using a model, but maybe this isn't possible. The piece of code that I am hitting with PostMan is this chunk:



[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
...
}


Maybe it is something I am doing incorrectly with postman, but I have been trying to use "=test" (as seen in other questions asked about this topic) in the value section of the body - x-www-form-urlencoded section with the key as jsonString and nothing. I have also tried using raw - text and raw - text/plain. I get the id so I know the url is correct. Any help with this would be greatly appreciated.



PostMan is set up like this currently:



POST http://localhost:8000/Edit/Test?id=111
key = id value = 111
Body - x-www-form-urlencoded
key = jsonString value = "=test"









share|improve this question
















This is probably something very basic, but I am having trouble figuring out where I am going wrong.



I am trying to grab a string from the body of a POST, but "jsonString" only shows as null. I also want to avoid using a model, but maybe this isn't possible. The piece of code that I am hitting with PostMan is this chunk:



[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
...
}


Maybe it is something I am doing incorrectly with postman, but I have been trying to use "=test" (as seen in other questions asked about this topic) in the value section of the body - x-www-form-urlencoded section with the key as jsonString and nothing. I have also tried using raw - text and raw - text/plain. I get the id so I know the url is correct. Any help with this would be greatly appreciated.



PostMan is set up like this currently:



POST http://localhost:8000/Edit/Test?id=111
key = id value = 111
Body - x-www-form-urlencoded
key = jsonString value = "=test"






c# asp.net-web-api asp.net-web-api2 postman asp.net-web-api-routing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 6 '18 at 10:43









Nkosi

112k16123190




112k16123190










asked Nov 28 '16 at 20:48









Robert PrineRobert Prine

5232715




5232715













  • Can you please provide your full http request including URL & body in your question.

    – matthensley.io
    Nov 28 '16 at 20:57













  • At least Request.Content.ReadAsStringAsync() should work.

    – Fabio
    Nov 28 '16 at 21:01






  • 1





    I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

    – Igor
    Nov 28 '16 at 21:23











  • Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

    – Michael Freidgeim
    Nov 18 '17 at 1:18











  • I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

    – Gineer
    Jun 7 '18 at 13:49



















  • Can you please provide your full http request including URL & body in your question.

    – matthensley.io
    Nov 28 '16 at 20:57













  • At least Request.Content.ReadAsStringAsync() should work.

    – Fabio
    Nov 28 '16 at 21:01






  • 1





    I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

    – Igor
    Nov 28 '16 at 21:23











  • Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

    – Michael Freidgeim
    Nov 18 '17 at 1:18











  • I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

    – Gineer
    Jun 7 '18 at 13:49

















Can you please provide your full http request including URL & body in your question.

– matthensley.io
Nov 28 '16 at 20:57







Can you please provide your full http request including URL & body in your question.

– matthensley.io
Nov 28 '16 at 20:57















At least Request.Content.ReadAsStringAsync() should work.

– Fabio
Nov 28 '16 at 21:01





At least Request.Content.ReadAsStringAsync() should work.

– Fabio
Nov 28 '16 at 21:01




1




1





I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

– Igor
Nov 28 '16 at 21:23





I believe this is possible. Set your header Content-Type: application/x-www-form-urlencoded. Body should be =test (nothing else).

– Igor
Nov 28 '16 at 21:23













Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

– Michael Freidgeim
Nov 18 '17 at 1:18





Related question for Asp.Net Core stackoverflow.com/questions/31952002/…

– Michael Freidgeim
Nov 18 '17 at 1:18













I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

– Gineer
Jun 7 '18 at 13:49





I have been batling with this for two days and after reading every article I could find about it, it turned out to be as simple as formatting the JSON string correctly in the WebRequest: The data must start and end with double quotes (I.E. Add double quotes inside your string of data around the json data) and if you then use single quotes throughout your json data it all plays nice.

– Gineer
Jun 7 '18 at 13:49












7 Answers
7






active

oldest

votes


















32














By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class



public class MyModel
{
public string Key {get; set;}
}

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] MyModel model)
{
... model.Key....
}


and a sent JSON like



{
key: "value"
}


Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.



I personally prefer the model binding because of the type safety.






share|improve this answer



















  • 2





    In question was mentioned: I also want to avoid using a model...

    – Fabio
    Nov 28 '16 at 21:08






  • 1





    @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

    – Ralf Bönning
    Nov 28 '16 at 21:10













  • This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

    – Codeman
    Jun 19 '18 at 23:48





















29














Referencing Parameter Binding in ASP.NET Web API




Using [FromBody]



To force Web API to read a simple type from the request body, add the
[FromBody] attribute to the parameter:



[Route("Edit/Test")]
[HttpPost]
public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }


In this example, Web API will use a media-type formatter to read the
value of jsonString from the request body. Here is an example client
request.



POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/json
Content-Length: 6

"test"


When a parameter has [FromBody], Web API uses the Content-Type header
to select a formatter. In this example, the content type is
"application/json" and the request body is a raw JSON string (not a
JSON object).




In the above example no model is needed if the data is provided in the correct format in the body.



For URL encoded a request would look like this



POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/x-www-form-urlencoded
Content-Length: 5

=test





share|improve this answer



















  • 2





    Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

    – Al Kepp
    Jan 31 '18 at 22:52



















9














When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:



"test"


Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers



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



 






share|improve this answer

































    5














    You are on the right track.



    On your header set



    Content-Type: application/x-www-form-urlencoded


    The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.





    See also POST string to ASP.NET Web Api application - returns null






    share|improve this answer

































      1














      I know this answer is kinda old and there are some very good answers who already solve the problem.



      In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.






      It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.





      This WILL NOT work (parameter still null):



      /* Action code */
      [HttpPost]
      public Weird NOURLAuthenticate([FromBody] Weird form) {
      return form;
      }
      /* Model class code */
      public class Weird {
      public string UserId {get;}
      public string UserPwd {get;}
      }


      This WILL work:



      /* Action code */
      [HttpPost]
      public Weird NOURLAuthenticate([FromBody] Weird form) {
      return form;
      }
      /* Model class code */
      public class Weird {
      public string UserId {get; set;}
      public string UserPwd {get; set;}
      }





      share|improve this answer































        1














        In my case I forgot to use
        JSON.stringify(bodyStuff).






        share|improve this answer































          0














          Finally got it working after 1 hour struggle.



          This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .



          For a new WebApi 2 application example:




          Postman (looks exactly, like below):




          POST    http://localhost:61402/api/values   [Send]

          Body
          (*) raw JSON (application/json) v

          "{ "key1": "value1" }"


          The port 61402 or url /api/values above, may be different for you.




          ValuesController.cs




          using Newtonsoft.Json;
          // ..

          // POST api/values
          [HttpPost]
          public object Post([FromBody]string jsonString)
          {
          // add reference to Newtonsoft.Json
          // using Newtonsoft.Json;

          // jsonString to myJsonObj
          var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

          // value1 is myJsonObj[key1]
          var valueOfkey1 = myJsonObj["key1"];

          return myJsonObj;
          }


          All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40853188%2ffrombody-string-parameter-is-giving-null%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            32














            By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class



            public class MyModel
            {
            public string Key {get; set;}
            }

            [Route("Edit/Test")]
            [HttpPost]
            public void Test(int id, [FromBody] MyModel model)
            {
            ... model.Key....
            }


            and a sent JSON like



            {
            key: "value"
            }


            Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.



            I personally prefer the model binding because of the type safety.






            share|improve this answer



















            • 2





              In question was mentioned: I also want to avoid using a model...

              – Fabio
              Nov 28 '16 at 21:08






            • 1





              @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

              – Ralf Bönning
              Nov 28 '16 at 21:10













            • This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

              – Codeman
              Jun 19 '18 at 23:48


















            32














            By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class



            public class MyModel
            {
            public string Key {get; set;}
            }

            [Route("Edit/Test")]
            [HttpPost]
            public void Test(int id, [FromBody] MyModel model)
            {
            ... model.Key....
            }


            and a sent JSON like



            {
            key: "value"
            }


            Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.



            I personally prefer the model binding because of the type safety.






            share|improve this answer



















            • 2





              In question was mentioned: I also want to avoid using a model...

              – Fabio
              Nov 28 '16 at 21:08






            • 1





              @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

              – Ralf Bönning
              Nov 28 '16 at 21:10













            • This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

              – Codeman
              Jun 19 '18 at 23:48
















            32












            32








            32







            By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class



            public class MyModel
            {
            public string Key {get; set;}
            }

            [Route("Edit/Test")]
            [HttpPost]
            public void Test(int id, [FromBody] MyModel model)
            {
            ... model.Key....
            }


            and a sent JSON like



            {
            key: "value"
            }


            Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.



            I personally prefer the model binding because of the type safety.






            share|improve this answer













            By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class



            public class MyModel
            {
            public string Key {get; set;}
            }

            [Route("Edit/Test")]
            [HttpPost]
            public void Test(int id, [FromBody] MyModel model)
            {
            ... model.Key....
            }


            and a sent JSON like



            {
            key: "value"
            }


            Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.



            I personally prefer the model binding because of the type safety.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 28 '16 at 21:03









            Ralf BönningRalf Bönning

            8,54352248




            8,54352248








            • 2





              In question was mentioned: I also want to avoid using a model...

              – Fabio
              Nov 28 '16 at 21:08






            • 1





              @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

              – Ralf Bönning
              Nov 28 '16 at 21:10













            • This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

              – Codeman
              Jun 19 '18 at 23:48
















            • 2





              In question was mentioned: I also want to avoid using a model...

              – Fabio
              Nov 28 '16 at 21:08






            • 1





              @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

              – Ralf Bönning
              Nov 28 '16 at 21:10













            • This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

              – Codeman
              Jun 19 '18 at 23:48










            2




            2





            In question was mentioned: I also want to avoid using a model...

            – Fabio
            Nov 28 '16 at 21:08





            In question was mentioned: I also want to avoid using a model...

            – Fabio
            Nov 28 '16 at 21:08




            1




            1





            @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

            – Ralf Bönning
            Nov 28 '16 at 21:10







            @Fabio - then [FromBody] will not work, because it tells the framework you want to bind the data to a model class. In order to avoid the binding, skip this parameter and access the sent data directly as hinted in the last paragraph. Hope that will help.

            – Ralf Bönning
            Nov 28 '16 at 21:10















            This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

            – Codeman
            Jun 19 '18 at 23:48







            This worked for me - you just have to use RAW instead of FORM in the POST options for POSTMan.

            – Codeman
            Jun 19 '18 at 23:48















            29














            Referencing Parameter Binding in ASP.NET Web API




            Using [FromBody]



            To force Web API to read a simple type from the request body, add the
            [FromBody] attribute to the parameter:



            [Route("Edit/Test")]
            [HttpPost]
            public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }


            In this example, Web API will use a media-type formatter to read the
            value of jsonString from the request body. Here is an example client
            request.



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/json
            Content-Length: 6

            "test"


            When a parameter has [FromBody], Web API uses the Content-Type header
            to select a formatter. In this example, the content type is
            "application/json" and the request body is a raw JSON string (not a
            JSON object).




            In the above example no model is needed if the data is provided in the correct format in the body.



            For URL encoded a request would look like this



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/x-www-form-urlencoded
            Content-Length: 5

            =test





            share|improve this answer



















            • 2





              Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

              – Al Kepp
              Jan 31 '18 at 22:52
















            29














            Referencing Parameter Binding in ASP.NET Web API




            Using [FromBody]



            To force Web API to read a simple type from the request body, add the
            [FromBody] attribute to the parameter:



            [Route("Edit/Test")]
            [HttpPost]
            public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }


            In this example, Web API will use a media-type formatter to read the
            value of jsonString from the request body. Here is an example client
            request.



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/json
            Content-Length: 6

            "test"


            When a parameter has [FromBody], Web API uses the Content-Type header
            to select a formatter. In this example, the content type is
            "application/json" and the request body is a raw JSON string (not a
            JSON object).




            In the above example no model is needed if the data is provided in the correct format in the body.



            For URL encoded a request would look like this



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/x-www-form-urlencoded
            Content-Length: 5

            =test





            share|improve this answer



















            • 2





              Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

              – Al Kepp
              Jan 31 '18 at 22:52














            29












            29








            29







            Referencing Parameter Binding in ASP.NET Web API




            Using [FromBody]



            To force Web API to read a simple type from the request body, add the
            [FromBody] attribute to the parameter:



            [Route("Edit/Test")]
            [HttpPost]
            public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }


            In this example, Web API will use a media-type formatter to read the
            value of jsonString from the request body. Here is an example client
            request.



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/json
            Content-Length: 6

            "test"


            When a parameter has [FromBody], Web API uses the Content-Type header
            to select a formatter. In this example, the content type is
            "application/json" and the request body is a raw JSON string (not a
            JSON object).




            In the above example no model is needed if the data is provided in the correct format in the body.



            For URL encoded a request would look like this



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/x-www-form-urlencoded
            Content-Length: 5

            =test





            share|improve this answer













            Referencing Parameter Binding in ASP.NET Web API




            Using [FromBody]



            To force Web API to read a simple type from the request body, add the
            [FromBody] attribute to the parameter:



            [Route("Edit/Test")]
            [HttpPost]
            public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }


            In this example, Web API will use a media-type formatter to read the
            value of jsonString from the request body. Here is an example client
            request.



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/json
            Content-Length: 6

            "test"


            When a parameter has [FromBody], Web API uses the Content-Type header
            to select a formatter. In this example, the content type is
            "application/json" and the request body is a raw JSON string (not a
            JSON object).




            In the above example no model is needed if the data is provided in the correct format in the body.



            For URL encoded a request would look like this



            POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
            User-Agent: Fiddler
            Host: localhost:8000
            Content-Type: application/x-www-form-urlencoded
            Content-Length: 5

            =test






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 29 '16 at 2:37









            NkosiNkosi

            112k16123190




            112k16123190








            • 2





              Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

              – Al Kepp
              Jan 31 '18 at 22:52














            • 2





              Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

              – Al Kepp
              Jan 31 '18 at 22:52








            2




            2





            Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

            – Al Kepp
            Jan 31 '18 at 22:52





            Exactly! That little = solves the problem. I remember it took me many days when I worked on my first project, because it was not mentioned in any web api book I had. :(

            – Al Kepp
            Jan 31 '18 at 22:52











            9














            When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:



            "test"


            Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers



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



             






            share|improve this answer






























              9














              When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:



              "test"


              Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers



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



               






              share|improve this answer




























                9












                9








                9







                When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:



                "test"


                Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers



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



                 






                share|improve this answer















                When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:



                "test"


                Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers



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



                 







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 10 '18 at 9:27

























                answered Jan 10 '18 at 9:20









                Michael FreidgeimMichael Freidgeim

                12.7k686109




                12.7k686109























                    5














                    You are on the right track.



                    On your header set



                    Content-Type: application/x-www-form-urlencoded


                    The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.





                    See also POST string to ASP.NET Web Api application - returns null






                    share|improve this answer






























                      5














                      You are on the right track.



                      On your header set



                      Content-Type: application/x-www-form-urlencoded


                      The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.





                      See also POST string to ASP.NET Web Api application - returns null






                      share|improve this answer




























                        5












                        5








                        5







                        You are on the right track.



                        On your header set



                        Content-Type: application/x-www-form-urlencoded


                        The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.





                        See also POST string to ASP.NET Web Api application - returns null






                        share|improve this answer















                        You are on the right track.



                        On your header set



                        Content-Type: application/x-www-form-urlencoded


                        The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.





                        See also POST string to ASP.NET Web Api application - returns null







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited May 23 '17 at 12:34









                        Community

                        11




                        11










                        answered Nov 28 '16 at 21:26









                        IgorIgor

                        39.4k349102




                        39.4k349102























                            1














                            I know this answer is kinda old and there are some very good answers who already solve the problem.



                            In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.






                            It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.





                            This WILL NOT work (parameter still null):



                            /* Action code */
                            [HttpPost]
                            public Weird NOURLAuthenticate([FromBody] Weird form) {
                            return form;
                            }
                            /* Model class code */
                            public class Weird {
                            public string UserId {get;}
                            public string UserPwd {get;}
                            }


                            This WILL work:



                            /* Action code */
                            [HttpPost]
                            public Weird NOURLAuthenticate([FromBody] Weird form) {
                            return form;
                            }
                            /* Model class code */
                            public class Weird {
                            public string UserId {get; set;}
                            public string UserPwd {get; set;}
                            }





                            share|improve this answer




























                              1














                              I know this answer is kinda old and there are some very good answers who already solve the problem.



                              In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.






                              It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.





                              This WILL NOT work (parameter still null):



                              /* Action code */
                              [HttpPost]
                              public Weird NOURLAuthenticate([FromBody] Weird form) {
                              return form;
                              }
                              /* Model class code */
                              public class Weird {
                              public string UserId {get;}
                              public string UserPwd {get;}
                              }


                              This WILL work:



                              /* Action code */
                              [HttpPost]
                              public Weird NOURLAuthenticate([FromBody] Weird form) {
                              return form;
                              }
                              /* Model class code */
                              public class Weird {
                              public string UserId {get; set;}
                              public string UserPwd {get; set;}
                              }





                              share|improve this answer


























                                1












                                1








                                1







                                I know this answer is kinda old and there are some very good answers who already solve the problem.



                                In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.






                                It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.





                                This WILL NOT work (parameter still null):



                                /* Action code */
                                [HttpPost]
                                public Weird NOURLAuthenticate([FromBody] Weird form) {
                                return form;
                                }
                                /* Model class code */
                                public class Weird {
                                public string UserId {get;}
                                public string UserPwd {get;}
                                }


                                This WILL work:



                                /* Action code */
                                [HttpPost]
                                public Weird NOURLAuthenticate([FromBody] Weird form) {
                                return form;
                                }
                                /* Model class code */
                                public class Weird {
                                public string UserId {get; set;}
                                public string UserPwd {get; set;}
                                }





                                share|improve this answer













                                I know this answer is kinda old and there are some very good answers who already solve the problem.



                                In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.






                                It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.





                                This WILL NOT work (parameter still null):



                                /* Action code */
                                [HttpPost]
                                public Weird NOURLAuthenticate([FromBody] Weird form) {
                                return form;
                                }
                                /* Model class code */
                                public class Weird {
                                public string UserId {get;}
                                public string UserPwd {get;}
                                }


                                This WILL work:



                                /* Action code */
                                [HttpPost]
                                public Weird NOURLAuthenticate([FromBody] Weird form) {
                                return form;
                                }
                                /* Model class code */
                                public class Weird {
                                public string UserId {get; set;}
                                public string UserPwd {get; set;}
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered May 1 '18 at 17:57









                                Some random IT boySome random IT boy

                                140112




                                140112























                                    1














                                    In my case I forgot to use
                                    JSON.stringify(bodyStuff).






                                    share|improve this answer




























                                      1














                                      In my case I forgot to use
                                      JSON.stringify(bodyStuff).






                                      share|improve this answer


























                                        1












                                        1








                                        1







                                        In my case I forgot to use
                                        JSON.stringify(bodyStuff).






                                        share|improve this answer













                                        In my case I forgot to use
                                        JSON.stringify(bodyStuff).







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jun 1 '18 at 8:36









                                        EugeneEugene

                                        12115




                                        12115























                                            0














                                            Finally got it working after 1 hour struggle.



                                            This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .



                                            For a new WebApi 2 application example:




                                            Postman (looks exactly, like below):




                                            POST    http://localhost:61402/api/values   [Send]

                                            Body
                                            (*) raw JSON (application/json) v

                                            "{ "key1": "value1" }"


                                            The port 61402 or url /api/values above, may be different for you.




                                            ValuesController.cs




                                            using Newtonsoft.Json;
                                            // ..

                                            // POST api/values
                                            [HttpPost]
                                            public object Post([FromBody]string jsonString)
                                            {
                                            // add reference to Newtonsoft.Json
                                            // using Newtonsoft.Json;

                                            // jsonString to myJsonObj
                                            var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

                                            // value1 is myJsonObj[key1]
                                            var valueOfkey1 = myJsonObj["key1"];

                                            return myJsonObj;
                                            }


                                            All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.






                                            share|improve this answer




























                                              0














                                              Finally got it working after 1 hour struggle.



                                              This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .



                                              For a new WebApi 2 application example:




                                              Postman (looks exactly, like below):




                                              POST    http://localhost:61402/api/values   [Send]

                                              Body
                                              (*) raw JSON (application/json) v

                                              "{ "key1": "value1" }"


                                              The port 61402 or url /api/values above, may be different for you.




                                              ValuesController.cs




                                              using Newtonsoft.Json;
                                              // ..

                                              // POST api/values
                                              [HttpPost]
                                              public object Post([FromBody]string jsonString)
                                              {
                                              // add reference to Newtonsoft.Json
                                              // using Newtonsoft.Json;

                                              // jsonString to myJsonObj
                                              var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

                                              // value1 is myJsonObj[key1]
                                              var valueOfkey1 = myJsonObj["key1"];

                                              return myJsonObj;
                                              }


                                              All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.






                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                Finally got it working after 1 hour struggle.



                                                This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .



                                                For a new WebApi 2 application example:




                                                Postman (looks exactly, like below):




                                                POST    http://localhost:61402/api/values   [Send]

                                                Body
                                                (*) raw JSON (application/json) v

                                                "{ "key1": "value1" }"


                                                The port 61402 or url /api/values above, may be different for you.




                                                ValuesController.cs




                                                using Newtonsoft.Json;
                                                // ..

                                                // POST api/values
                                                [HttpPost]
                                                public object Post([FromBody]string jsonString)
                                                {
                                                // add reference to Newtonsoft.Json
                                                // using Newtonsoft.Json;

                                                // jsonString to myJsonObj
                                                var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

                                                // value1 is myJsonObj[key1]
                                                var valueOfkey1 = myJsonObj["key1"];

                                                return myJsonObj;
                                                }


                                                All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.






                                                share|improve this answer













                                                Finally got it working after 1 hour struggle.



                                                This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .



                                                For a new WebApi 2 application example:




                                                Postman (looks exactly, like below):




                                                POST    http://localhost:61402/api/values   [Send]

                                                Body
                                                (*) raw JSON (application/json) v

                                                "{ "key1": "value1" }"


                                                The port 61402 or url /api/values above, may be different for you.




                                                ValuesController.cs




                                                using Newtonsoft.Json;
                                                // ..

                                                // POST api/values
                                                [HttpPost]
                                                public object Post([FromBody]string jsonString)
                                                {
                                                // add reference to Newtonsoft.Json
                                                // using Newtonsoft.Json;

                                                // jsonString to myJsonObj
                                                var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

                                                // value1 is myJsonObj[key1]
                                                var valueOfkey1 = myJsonObj["key1"];

                                                return myJsonObj;
                                                }


                                                All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 24 '18 at 11:12









                                                Manohar Reddy PoreddyManohar Reddy Poreddy

                                                4,8834845




                                                4,8834845






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40853188%2ffrombody-string-parameter-is-giving-null%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    404 Error Contact Form 7 ajax form submitting

                                                    How to know if a Active Directory user can login interactively

                                                    TypeError: fit_transform() missing 1 required positional argument: 'X'