0

This may be dumb question but am struggling with this i cannot fetch the value from web api using ajax, let me explain my problem in detail i have created simple web api by using ajax i need to fetch the value how can i achieve this let me post my code what i have tried so far:

Webapi code:

  [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [HttpGet]
        [Route("~/api/getail/{id}/{criteriaid}")]
        public IHttpActionResult GetIncidentByResourceID(int id, int criteriaid)
        {
            IncidentDisplayApiModelCollection collection = objIncidentApiManager.GetDisplayList(id, criteriaid, 4);
            return Json(collection);
        }

This is sample ajax request:

   <script src="js/jquery-3.2.0.min.js"></script>
              <script >
       $(document).ready(function(){
       $.ajax({
    url: "http://localhost:8080/sf/api/getail/1848/29",
    dataType: "json",
     success: function( response ) {
        console.log( response ); // server response
    },
    error: function( response ) {
        console.log( response ); // server response
    }
});

});
       </script>

what am getting in firefox console is :

Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(), 9 more… }  index.html:59:9

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/sf/api/getail/1848/29. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I have downloaded cors in nuget manager and added confi.enablecors(); in webapi config. can someone help me how to resolve this thanks in advance!!

M.Yogeshwaran
  • 1,419
  • 4
  • 22
  • 48

1 Answers1

0

The origins parameter should contain the value of the Origin request header.

When request is made from page with file:// URI, browsers set the Origin header to be null (string) (I've tested in Firefox and Chrome).

So, try to add "null" to the origins parameter:

    [EnableCors(origins: "null", headers: "*", methods: "*")]

but i'm not sure this will work (such an unusual value!)

Or, simpler, just set it to be "*" to allow requests from any origins:

    [EnableCors(origins: "*", headers: "*", methods: "*")]

NOTE: (!) When deploying to production, consider carefully before allowing requests from any origin. It means that literally any website can make AJAX calls to your web API.

Hope it helps

Iv Ov
  • 357
  • 3
  • 6