1

I have developed a Web API in asp.net 5 where I am fetching a list of books available in the database and returning it as JSON. The API is running at Port number 5000 (http://localhost:5000/api/bookstore)

Now I have a website set up on my PC with a single index.html file where I am trying to consuming the above API endpoint. The website is running at a different port (52786).

Initially with dataType: 'json' I was getting the following console error:

XMLHttpRequest cannot load http://localhost:5000/api/bookstore. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52786' is therefore not allowed access.

To avoid above 'Access-Control-Allow-Origin' error I used dataType: 'jsonp', (as suggested by Gavin here). Using jsonp apparently removes the error from console but nothing is showing up when I am running the page. How would I know whether the endpoint is at all being hit and if it is why the data is not being pulled?

But when I am running http://localhost:5000/api/bookstore separately on the browser it is giving me data perfectly.

Below is the code snippet I used to invoke API endpoint using jQuery and ajax:

<script type="text/javascript">
  $(document).ready(function () {
    //jQuery.support.cors = true;
    $.ajax({
      type: "GET",
      url: "http://localhost:5000/api/bookstore",
      dataType: 'jsonp',
      success: function (data) {
        alert(data);
        $("#response").html(data);
      },
      error: function (err) {

      }
    });
  });
</script>

NB: Both the website and the Web API port are running.

UPDATE (Screenshots)

Image 1: Console messages when invoking the endpoint from another website (as could be seen I am running Chrome with disable-web-security in order to bypass CORS. I was successful in the past by doing this in dev environment so tried here as well.

enter image description here

Image 2: Network: enter image description here

Image 3: API Source enter image description here

Community
  • 1
  • 1
Subrata Sarkar
  • 2,975
  • 6
  • 45
  • 85
  • You can't just change the datatype expected back in the request on the client to JSONP - you need to change how the server returns data for that to work. However, a much simpler idea is to enable CORS on your WebApi, see [this question](http://stackoverflow.com/questions/27504256/mvc-web-api-no-access-control-allow-origin-header-is-present-on-the-requested) for instructions how to achieve that – Rory McCrossan Jan 05 '16 at 11:03
  • http://stackoverflow.com/questions/23746034/enabling-cross-domain-asp-net-web-api – Umesh Sehta Jan 05 '16 at 11:03
  • Thank you for quick replies! I will read and try in my solution. – Subrata Sarkar Jan 05 '16 at 11:04
  • I am using VS code for my Web API development. In `project.json` file the version resolving is `"Microsoft.AspNet.WebApi.Cors": "5.2.3",`. `dnu restore` restores `project.lock.json`. But when building I am receiving `D:\Projects\aspnet\apiservice\project.json(0,0): error NU1002: The dependency Microsoft.AspNet.WebApi.Core 5.2.3 in project apiservice does not support framework DNXCore,Version=v5.0`. One other thing. This project was generated using `Yeoman`. I don't have any `WebApiConfig.cs` in the project. Even the assembly resolves I have no idea of where to put `config.EnableCors(...);` – Subrata Sarkar Jan 05 '16 at 12:20
  • @NiladriSarkar any luck? I'm also having the same issue. It looks like .net core didn't get Cors support so far. – eestein Apr 12 '16 at 20:33

2 Answers2

0

The API should have the following for allowing cross origin request.

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

Also, make sure that the Handler Mappings are present

<handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
        </handlers>
Rajat
  • 410
  • 4
  • 19
0

I got it to work in the following way.

Step 1: In Startup.cs inside ConfigureServices method we need to add CORS like this:

public void ConfigureServices(IServiceCollection services)
{
  //CORS
  services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
}

Then we need to add the attribute EnableCors to methods we need to access externally from a different website, which exposes these methods to bypass Access-Control-Allow-Origin error. With CORS enables we need not to run a browser with disabled security mode!

[EnableCors("AllowAll")] //This allows the method to be called from anywhere.
public async Task<object> Recipients([FromBody] dynamic jsonText)
{
  var result = await getYourResultFromSomewhere();
  return result;
}

Let me know if this is of any help!

Subrata Sarkar
  • 2,975
  • 6
  • 45
  • 85