0

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

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

3 Comments

This works! But I have to remove the custom header in my Web.Config for this to work. +1
yes. no need to configure web config if we are adding the response headers.
Works with GET, but not with POST. See updates above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.