0

I have an array that I'm converting to JSON using JSON.stringify

const arrayOfUpdatesAsJSON = JSON.stringify(this.ArrayOfTextUpdates);

This outputs some valid JSON.

[{"key":"AgentName","value":"Joe Blogs"},{"key":"AgentEmail","value":"[email protected]"}]

As I'm going to be sending JSON to the server I set the content type to application/json

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
  })
};

When a button is pressed I make the request with the url, body and header.

try {
  this.httpservice
    .post(
      url,
      arrayOfUpdatesAsJSON,
      httpOptions
    )
    .subscribe(result => {
      console.log("Post success: ", result);
    });
} catch (error) {
  console.log(error);
}

This works fine and hits the method I'm expecting inside the api.

    [HttpPost("{id:length(24)}", Name = "UpdateLoan")]
    public IActionResult Update(string id, string jsonString)
    {
        Console.WriteLine(jsonString);
        ... and some other stuff
    }

The ID is populated inside the url builder which populates ok. I would then expect the contents of my variable jsonString inside the api to be populated with the json of my request however it is always null. What am I missing?

2
  • You are sending an array, but expect query parameters (since there is no complex model defined on your controller and webapi doesn't expect multipart/form-data/application/x-www-form-urlencoded) Commented Mar 28, 2019 at 13:13
  • 1
    You're sending JSON not a string. Even though the JSON is effectively a "string", you cannot bind it directly to a C# string, because it's interpreted as an object. You'd need to send it as x-www-form-urlencoded, like data: { jsonString: JSON.stringify(foo) }. Or, you can bind it to something like List<KeyValuePair>. I'm not 100% sure that will work, but it's the closest construction to the JSON you're sending. Commented Mar 28, 2019 at 13:21

1 Answer 1

1

Firstly you need to mark jsonString with [FromBody] to tell model binder bind the parameter from posted json. And because you are expecting plain string value you need to pass valid json string (not object) so you need to call additional JSON.stringify in javascript

const jsonArray = JSON.stringify(this.ArrayOfTextUpdates);
const arrayOfUpdatesAsJSON = JSON.stringify(jsonArray);

this.httpservice
    .post(
      url,
      arrayOfUpdatesAsJSON,
      httpOptions
)

Controller

[HttpPost("{id:length(24)}", Name = "UpdateLoan")]
public IActionResult Update(string id, [FromBody] string jsonString)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.