Angular POST request to C# API

Paul Weiler
3 min readFeb 6, 2020

This post covers a lot of info on both the C# and Angular side of the request. If you simply want a working code example (with advanced error handling) check out the GitHub link at the bottom of the post.

Diving Into the Angular request:

Inside your angular service you have a standard API call:

getCompanies(companyid = 0): Observable<Company> {
return this.http.get<Company>('http://localhost:8080/api/GetCompany',{params: new HttpParams().set('companyid', companyid.toString()) });
}

A few things to note:

  • The first parameter of the GET or POST request is the url. This can be simplified by using a url provider in the app.module.ts, but for this example it is explicit.
  • The get or post request requires you to specify the return type of the request. In this case I specified the Company object but you could also specify it by casting the return object to the type you expect explicitly (see bold text below):
getCompanies(companyid = 0): Observable<Company> {
return this.http.get<Company>('http://localhost:8080/api/GetCompany',{params: new HttpParams().set('companyid', companyid.toString())
}).pipe(map(res => <Company>res));
}

Note: When you pass parameters using HttpParams they must be string values. It is possible to pass complex objects, but they must be stringified using JSON.stringify()

Handling Angular errors (simply)

Adding some basic error handling code in Angular to dump the returned object to console if your Controller returns an invalid object is pretty simple using the rxjs catchError function:

getCompanies(companyid = 0): Observable<Company> {
return this.http.get<Company>('http://localhost:8080/api/GetCompany',{params: new HttpParams().set('companyid', companyid.toString())
}).catchError(x=>console.log(JSON.stringify(x)));
}

C# Controller

This is the part that listens for requests from the Angular service. Note that the bold code is the listener method. The top part of the code is simply how to initialize the controller, and the route.

[Route("api")]
[ApiController] //so we dont have to call model.isValid any more. returns 400 status code if model invalid
public class MyController : Controller{ [HttpGet(“GetCompany”)]
public ActionResult<Company> GetCompany(int companyid)
{
return new Company(companyid);
}
}

On the C# side:

  • Note that the parameters you passed from Angular match exactly. The order and spelling must be exactly the same (otherwise the route won’t match)
  • A route attribute annotation such as HttpGet or HttpPut may be required (depending on how you set up your Startup.cs). I generally put them by default.
  • If you use route annotations (like HttpGet()) the parameter being passed to them must be exactly as specified in Angular, but the method itself can be named anything.
  • Note that the return type is ActionResult<Company>because this lets you send Angular any object, but it expects the object to be of type Company. This is useful because you can also pass back error objects. For example:

Handling C# Errors: notifying Angular of a problem

[HttpGet(“GetCompany”)]
public ActionResult<Company> GetCompany(int companyid){
try{
return new Company(companyid);
}
catch(Exception e){
return StatusCode(500,Json(“ERROR: ”+e.Message));
}
}

Tip: Always cast the string text in the StatusCode() to a Json object, because Angular expects an object from this API call, not a plain string. If you don’t do this the Angular catchError function may fire on a valid API response. See this StackOverflow post for more info.

Now that you’ve understood the basics of how everything is put together feel free to take a look at the complete gist linked below. It contains some more advanced error handling, as well as examples for both POST and GET requests.

--

--

Paul Weiler
0 Followers

Backend JS dev who enjoys writing about JS/TS and AWS. Im often thinking of new topics while rock climbing