簡體   English   中英

為什么我的角度控制器沒有擊中我的Web Api控制器?

[英]Why isn't my angular controller hitting my Web Api Controller?

我試圖從服務器獲取測試客戶列表。 我知道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();
    }
}

我錯過了什么?

默認情況下, Web API不允許遠程連接。

這稱為Cross-origin resource sharingCORS )。

Web API 2.2通過提供EnableCorsAttribute可以輕松啟用CORS

基本用法

[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM