为什么我的角度控制器没有击中我的Web Api控制器?

时间:2014-12-03 13:54:20

标签: c# asp.net angularjs asp.net-web-api

我正在尝试从服务器获取测试客户列表。我知道Web API控制器正在从数据库接收数据,因为我有围绕它的单元/集成测试;但是,当我尝试将数据拉到角度控制器时,我会收到500状态代码。

角度控制器:

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();
    }
}

我错过了什么?

1 个答案:

答案 0 :(得分:2)

Web API默认情况下不允许远程连接。

这称为Cross-origin resource sharingCORS)。

Web API 2.2可以通过提供CORS轻松启用EnableCorsAttribute

基本用法

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

属性定义

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

要在全球范围内启用CORS

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

您还需要从nuget

安装CORS包
Install-Package Microsoft.AspNet.WebApi.Cors