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

All we need is an easy explanation of the problem, so here it is.

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: enter image description here

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.

enter image description here

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply