Search code examples
c#jsonangularangular7

C# [HttpPost] string value through angular http.post becomes null


My C# post method looks

[HttpPost]
public void mymethod(string id) {...}

I am trying to post string value from angular http.post like this but value reaches to C# method as null.

const mystr = 'mystring';
this.http.post('myurl', mystr);

What I tried

{id: mystr}
JSON.stringify({id: mystr})

Note: Sending id value with [HttpGet("{id}")] works well but mystr may contains '/' value so fails whenever '/' contains.

When I replace mymethod signature to ([FromBody] string id) I get 400 Bad Request.


Solution

  • Use encodeValue on mystr on angular. In C# API id you should get decoded value.

    https://angular.io/api/common/http/HttpUrlEncodingCodec