Joseph
Joseph

Reputation: 522

CORS issue with AngularJS and ASP Controller API hosted in other server within local network

I have an ASP application hosted in a server within a local network. When I call an OPTION request from AngularJS, it returns with a 200 status but with an error.

This is my GET code in Angular:

var config = {
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Accept',
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}

Then this is how I return JSON data from my ASP application:

    public class TablesController : Controller
    {
        // GET: Tables
        [System.Web.Http.HttpGet]
        public ActionResult Index()
        {
            Database db = new Database();
            Result res = new Result();
            res = db.Get();

            if (Response != null)
            {
                Response.AddHeader("Access-Control-Allow-Origin", "*");
                Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
            }

            return new JsonResult()
            {
                Data = res,
                ContentType = "application/json",
                MaxJsonLength = Int32.MaxValue,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            //return View();
        }
    }

I tried to add custom headers in my Web.config:

<httpProtocol>      
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />        
  </customHeaders>
</httpProtocol>

Then it is giving me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:///tables. (Reason: CORS header >‘Access-Control-Allow-Origin’ does not match ‘(null)’).

When I removed it, it is giving me this error:

(Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

And I have this included in my WebAppConfig.cs:

        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

I can't seem to make it work to return data to Angular. Any suggestions are appreciated.

UPDATE:

Can make it to work with GET, but now having problems with POST:

Angular:

function addName(user) {
    alert("about to post!")
    $http.post('http://<IPAddress>/tables/create', user, config)
      .then(function (res) {
          $scope.getNames();
      });
}

ASP.Net

   [System.Web.Http.HttpPost]
    public ActionResult Create([FromBody] Users2 value)
    {
        Database db = new Helpers.Database();
        Result res = new Helpers.Result();

        res = db.Post(value.Name, value.Location);

        if (Response != null)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
            Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");
        }


        return Json(res, JsonRequestBehavior.AllowGet);
    }

error:

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Upvotes: 0

Views: 125

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

remove the access allow headers from the angular request.

var config = {
    headers: {
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}

Add the access allow methods in the asp

 Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
 Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");

Upvotes: 1

Related Questions