1

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.

Ramesh
  • 1,041
  • 15
  • 39

3 Answers3

0

for your scenario you need a small change, just come with a Model of data you want to receive in POST request. Something like :-

public class CustomData {
   string id {get; set;}
}

and then tweak your API and make it aware that it has to recieve something from from request's body

So, instead of

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

use this

[HttpPost]
public void mymethod([FromBody] CustomData data) {...}
manish
  • 1,450
  • 8
  • 13
0

could you try changing the way you send from angular as the following

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

this.http.post('myurl', 'string value', { headers: headers }) ;

if 'applicaiton/json' does not work please try to change it to 'application/x-www-form-urlencoded'

0

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

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

Miq
  • 3,931
  • 2
  • 18
  • 32
  • simple example will be appreciated. – Ramesh Mar 28 '19 at 07:08
  • I updated my answer. I'm not an expert in angular, but in general, you need to change slashes to %2F so they will not be treated by C# as path delimiters. – Miq Mar 28 '19 at 07:15