CORS Issue same controller, one method is ok, other one is not

早过忘川 提交于 2019-12-11 01:45:50

问题


Very strange error I'm experiencing.

I have two methods in controller which are called by angular js http get event.

First one works fine, second one is throwing CORS error, not sure how is that possible since both of them are in same controller.

This is the error I'm getting:

These are the calls I'm doing in 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);
    });

And the controller methods:

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

I'm able to hit both methods, I have breakpoints in both of the methods, but not sure why is complaining about CORS on the first one.


回答1:


Calling methods using CORS from a Web browser makes Web API being called first with an OPTIONS request (example at the end of this article).

This way, the browser knows if it can call the requested API.

In your case, the call to your endpoint seems to be crashing, which means the HTTP 500 error does not contain any CORS headers.

This explains why the web browser complaning about CORS HTTP Header missing: Reason: CORS Header 'Access-Control-Allow-Origin' missing.

If you fix your method, then HTTP OPTIONS should be ok, and the CORS erros would go away.



来源:https://stackoverflow.com/questions/39497920/cors-issue-same-controller-one-method-is-ok-other-one-is-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!