Hypenate
Hypenate

Reputation: 2064

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.

Upvotes: 3

Views: 6300

Answers (3)

Stanislav
Stanislav

Reputation: 4549

In Agnular 10 the following works:

let bar = 'Hello World!';
this._httpClient.post('api/GetDetails', '=' + bar, { 
    headers: new HttpHeaders({ 
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' 
    }) 
})

PS: the way I figured it out was by comparing curls generated from dev tools for the working request in AngularJs and not working request in Angular 10

Upvotes: 0

Thierry Prost
Thierry Prost

Reputation: 1025

2 ways, depending on whether you have control over back or front end.

1. Angular-service Use header application/json; charset=utf-8 as described here and here (note the charset)

2. API The other one is to build a custom string-binder derived which spits out a string.

[HttpPost]
public JsonResult GetDetails([ModelBinder(typeof(StringBinder))] string bar) { ... }

where

public class StringBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        using (var sr = new StreamReader(bindingContext.HttpContext.Request.Body))
            Body = sr.ReadToEnd();


        bindingContext.Result = ModelBindingResult.Success(Model);

        return Task.CompletedTask;
    }
}

Upvotes: 1

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Try this :

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

http.post('/api/GetDetails', body).subscribe();

Upvotes: 5

Related Questions