0

I am working on a project that use ASP.NET MVC, AngularJs and WebApi 2.0. I am calling a web api controller from angularjs. I must create the first web api controller. So I updated the start_application in the global.asax, adding the following code:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Use camel case for JSON data.
    //config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Then I created the first web api controller (first time I created it inside the folder controller but it did not work and I thought it was going in conflict with mvc routing, so I created a folder WebApi\Controllers):

[Route("api/Countries")]
public class CountriesController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetCountries()
    { //<-- Here, I put a breakpoint and never go in
        return Ok();
    }
}

I have created a factory in angularjs:

intranet
    .factory("countriesService", function ($resource, ENDPOINT) {
        return {
            countries: $resource(ENDPOINT + "api/Countries/")
        };
    });

And the i call the service in an angular controller:

$scope.getCountries = function () {
    new countriesService
            .countries
            .query({ }, getCountriesSuccess, getCountriesError);
};

I obtain the following error:

angular.js:9818 GET http://localhost:50407/api/Countries 404 (Not Found)

1
  • yes, not found... I think it is a routing problem... or perhaps a problem with the configuration of web api Commented Oct 3, 2016 at 11:23

1 Answer 1

0

The order I configure the routing is very important... My configuration was

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);

It must become as following

AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register); 
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.