asp.net - CORS 发出相同的 Controller ,一种方法可以,另一种方法不行

标签 asp.net angularjs asp.net-web-api angular-http

我遇到了非常奇怪的错误。

我在 Controller 中有两种方法,它们由 angular js http get 事件调用。

第一个工作正常,第二个是抛出 CORS 错误,不确定这怎么可能,因为它们都在同一个 Controller 中。

这是我得到的错误:enter image description here

这些是我在 angularjs 中所做的调用:

 $http({
        url: 'http://localhost:52876/api/Admin/GetLoanInfo',
        method: "GET",
        params: { loanID: querystringParam }
    }).success(function (data, status) {
        console.log(data);
        $scope.LoanDetailsVM.LoanStatus = data.LoanStatus;
    }).error(function (data, status) {
        console.log(data);
    });

    $http({
        url: 'http://localhost:52876/api/Admin/GetLoanCovenants',
        method: "GET",
        params: { loanID: querystringParam }
    }).success(function (data, status) {
        console.log(data);
    }).error(function (data, status) {
        console.log(data);
    });

和 Controller 方法:
[HttpGet]
[Route("api/Admin/GetLoanInfo")]
public async Task<IHttpActionResult> GetLoanInfo(int loanID)
{

        LoanApplication newApplication = null;
        newApplication = db.LoanApplications.FirstOrDefault(s => s.LoanId == loanID);
        return Ok(newApplication);
}


[HttpGet]
[Route("api/Admin/GetLoanCovenants")]
public async Task<IHttpActionResult> GetLoanCovenants(int loanID)
{
        LoanCovenant newCovenant = null;
        newCovenant = db.LoanCovenants.FirstOrDefault(s => s.LoanID == loanID);
        return Ok(newCovenant);
}

我能够使用这两种方法,我在两种方法中都有断点,但不确定为什么在第一种方法上提示 CORS。

enter image description here

最佳答案

从 Web 浏览器使用 CORS 调用方法会使 Web API 首先被调用 OPTIONS请求(例如 at the end of this article )。

这样,浏览器知道 如果它可以调用请求的API。

在您的情况下,对您的端点的调用似乎崩溃了,这意味着 HTTP 500 错误不包含任何 CORS header 。

这解释了为什么 Web 浏览器提示 CORS HTTP Header 丢失:Reason: CORS Header 'Access-Control-Allow-Origin' missing .

如果你修复了你的方法,那么 HTTP OPTIONS应该没问题,CORS 错误就会消失。

关于asp.net - CORS 发出相同的 Controller ,一种方法可以,另一种方法不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497920/

相关文章:

javascript - Angularjs - Uncaught Error : [$injector:modulerr]

javascript - $scope 在我的导航栏 Controller 中不起作用?

java - 如何克服未发现转换器错误

c# - 将 POST 参数传递给 WEB API2

asp.net-mvc - Web API错误: The 'ObjectContent` 1' type failed to serialize the response body for content type

c# - Json 字符串在 web-api 中被转义

asp.net - Microsoft 应用程序 - 重定向 URI 允许 'localhost' 但不允许 '127.0.0.1'

c# - IE11 用户代理

asp.net - 在 IIS7 中访问图像时出现 500 内部服务器错误

c# - Entity Framework 6 的动态 MySQL 数据库连接