簡體   English   中英

ASP.Net MVC 應用程序在進行 Web API 調用時拋出 403 錯誤

[英]ASP.Net MVC application throws 403 error while making a Web API call

我有一個 MVC 應用程序的問題,它有一個 class 來自ApiController的后代:

[Authorize]
public class WidgetController : ApiController
{
    // POST: api/Widget/GetWidgets
    [HttpPost]
    [ActionName("GetWidgets")]
    public List<WidgetItem> GetWidgets(WidgetQueryParams parms)
    {
        // ...
    }

    // ...
}

這是在 WebApiConfig.cs 中配置的:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ExceptionHandlingAttribute());

        config.MapHttpAttributeRoutes();

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

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

該方法是從建立在 AngularJS 之上的 JavaScript 調用的:

function () {
    'use strict';

    angular.module('WidgetApp').factory('DataContext', ['$http', '$q', DataContext]);

    function DataContext($http, $q) {
        var service = {
            // ...
            WebAPIPostWithData: WebAPIPostWithData,
            // ...
        };
        return service;
    
        function WebApiPostWithData(Controller, Action, data) {
            var url = "api/" + Controller + "/" + Action;
            var deferred = $q.defer();

            $http.post(url, data)
                .success(function (httpResult) {
                    deferred.resuilve(httpResult);
                }).error(response) {
                    deferred.reject(response);
                    throw "Exception: DataContext/WebAPIPostWithData - Error while calling the url '" + url + "'. Message: " + response.ExceptionMessage;
                })
            return deferred.promise;
        }
    }
})();

在運行時,JavaScript 進入DataContext.WebAPIPostWithData()並調用$http.post() 當調用返回時,我看到代碼在我放在.error() function 上的斷點處停止,響應是 403 錯誤。 作為實驗,我修改了WidgetController中的代碼,因此GetWidgets()方法被修飾為[HttpGet]方法而不是[HttpPost]並且程序在該方法的斷點處停止。

在這一點上我完全不知所措。 為什么調用作為 HTTP POST 操作調用時返回 403 錯誤,但在作為 HTTP GET 操作調用時工作正常? 有沒有人對可能出什么問題有任何想法?

可能是 CORS 飛行前檢查錯誤。 GET請求沒有這些限制,但是POST請求有。 對於飛行前檢查錯誤,它通常會這樣說。 你能檢查一下它在 Postman 中是否有效嗎? 如果它在 Postman 中有效,但在您的應用中無效,則表明這是飛行前檢查問題。

您可能會發現以下答案也很有用: Response for preflight 403 forbidden

也許您有權從 API 讀取但不能寫入?

暫無
暫無

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

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