Nick Nick - 2 months ago 21
AngularJS Question

Angular 2 Calling .Net Controller from the Same Project

I'm trying to make a call to my .net API controller from my Angular 2 service but I keep getting a 404 that it's not found. I'm able to browse to the api function in the browser and return data just fine (ie: http://localhost:51849/api/Application/Get). Any clue where I'm going wrong? I've done similar work in AngularJS 1 like this with no issue. Any help is appreciated. Thanks!

The Angular 2 service call:

getApplications(): Promise<Application[]> {
return this.http.get('/api/Application/Get/')
.toPromise()
.then(response => response.json().data as Application[])
.catch(this.handleError);
}


The .Net API controller function:

public class ApplicationController : ApiController
{
public HttpResponseMessage Get()
{
var applicationsModel = new ApplicationsModel();

try
{
var applications = new ApplicationService().GetAllApplications();

foreach (var application in applications)
{
applicationsModel.Applications.Add(new Application(application.MWF_ApplicationID, (int)application.MWF_Priority, application.MWF_DateCreated.ToString("MM/dd/yyyy"), "", "", 0, 0));
}

}
catch(Exception e)
{
applicationsModel.Error = "Error getting applications: " + e.Message;
}

return this.Request.CreateResponse(HttpStatusCode.OK, applicationsModel);
}
}

Answer

For an Api controller you would call this.http.get("/api/Application")

It should automagically figure out that it should call the Get() function for you.

This document is a good read for more information: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api