Why didn't my angular controller hit my api web controller?

I am trying to get a list of test clients from a server. I know the web API controller is getting data from the DB because I have unit / integration tests; however, when I try to pull data to my angular controller, I get a 500 status code.

Angular Controller:

var surchargeIndex = angular.module('surchargeIndex', []);

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService) {
    $scope.customers = { Key: "", Value: "" };
    customerService.getTest($scope);
});

surchargeIndex.service('customerService', [
    '$http', function($http) {
        this.getTest = function ($scope) {
            return $http({
                method: "GET",
                url: "api/Customer/GetTest",
            })
            .success(function (data) {
                $scope.customers = data;
            })
            .error(function () {
                $scope.error = "Failed to load customers!";
            });
        }
    }
]);

      

Web Api:

[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
    private readonly ICustomerService _service;

    public CustomerController(ICustomerService service)
    {
        _service = service;
    }

    [Route("GetTest"), HttpGet]
    public IEnumerable<IJsonResult> GetTest()
    {
        return _service.GetTest();
    }
}

      

What am I missing?

+3


source to share


1 answer


Web API

does not allow remote connections by default.

This is called Cross-origin resource sharing

( CORS

).

Web API 2.2

makes it easy to enable CORS

by providing EnableCorsAttribute

.

Primary use

[EnableCors("*", "*", "*")]
public class ResourcesController : ApiController
{
    ...

      

Attribute definition



[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public EnableCorsAttribute(
    string origins,
    string headers,
    string methods
)

      

To enable CORS

globally use

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.example.com", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}

      

You will also need to install the CORS package with nuget

Install-Package Microsoft.AspNet.WebApi.Cors

      

+2


source







All Articles