Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string from Angular to API

I want to fill in one string parameter in my ASP.NET Core MVC API controller via Angular.

I have this working call:

API

//A class to wrap my string
public class Foo
{
  public string bar { get; set; }
}

[HttpPost]
public JsonResult GetDetails([FromBody] Foo bar) { ... }

Angular (service)

public get() {
  let bar: any = new Object();
  bar.foo = 'Hello World';

  return this._httpClient.post('api/GetDetails', bar).toPromise();
}

But what I really want is pass a string without having to wrap it in a class like this:

API

[HttpPost]
public JsonResult GetDetails([FromBody] string bar) { ... }

Angular (service)

public get() {
let bar: string = "Hello World";

return this._httpClient.post('api/GetDetails', bar).toPromise();
}

But I get errors like it's an Unsupported Media Type or 'bar' stays null.
What is the right syntax to just pass one value?
The other thing is, I can pass an integer from Angular to the API just fine but not a string.

like image 743
Hypenate Avatar asked May 22 '26 22:05

Hypenate


1 Answers

Try this :

let bar = JSON.stringify({'foo' : 'Hello World'});
let body = new HttpParams();
body = body.set('bar', bar);

http.post('/api/GetDetails', body).subscribe();
like image 135
Creative Learner Avatar answered May 25 '26 11:05

Creative Learner