Search code examples
javascriptc#angularhttp-post

Angular HttpClient post cannot send simple string parameter


I want to send a request to a C# service which has a string as its parameter. I wrote an angular service like this:

export class CategoryService {

  constructor(private http: HttpClient) { }
  getCategory(categoryName: string): Observable<Category> {
    console.log(categoryName);
    return this.http.post("/category/GetCategory", { categoryName: categoryName }, { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
  }

I also tried:

export class CategoryService {

  constructor(private http: HttpClient) { }
  getCategory(categoryName: string): Observable<Category> {
    console.log(categoryName);
    return this.http.post("/category/GetCategory",  categoryName , { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
  }

But when they both successfully send the request, the parameter is always null. My C# service is:

    [HttpPost]
    public IActionResult GetCategory([FromBody]string categoryName)

Solution

  • I found the solution here: Angular2 - Http POST request parameters I also should remove [FromBody] from my service parameter.