Unable to access HTTP based Web Api from HTTPS based SharePoint site

Frank Martin 476 Reputation points
2020-12-21T11:25:13.91+00:00

My site collection is accessible as:

https://myserver/sites/cfp

I have a Web API with just one method which is accessible as:

http://localhost:10000/api/CFP/GetCustomerName

I can access the above API using Jquery/Ajax from an HTML page as well as from Postman. But when I try to access it from my SharePoint page I get "undefined" alert on screen as I am displaying error in alert.

I believe this is due to CORS and after that I even enabled CORS but still the problem remains. My Web API controller looks like this:

[HttpGet]
        [EnableCors(origins: "https://myserver", headers: "*", methods: "*")]
        public IHttpActionResult GetCustomerName (string num)
        {
            return Json(new
            {
                success = true,
                message = "My Name "+ num,
            });
        }

What am I doing wrong?

SharePoint Server
SharePoint Server
A family of Microsoft on-premises document management and storage systems.
2,365 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
341 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,619 questions
{count} votes

Accepted answer
  1. Frank Martin 476 Reputation points
    2020-12-22T10:34:41.147+00:00

    I finally found real reason as to why it was happening. This was happening in IE:

    http://web.archive.org/web/20150906055648/http://bugs.jquery.com/ticket/10660

    Solution is to use following before your AJAX request.

    $.support.cors = true;
    

    Also your request and Web API must use same protocol i.e. you cannot call HTTP while you are on HTTPS. So in my case I changed my Web API to be hosted on HTTPS and now it works.


1 additional answer

Sort by: Most helpful
  1. Frank Martin 476 Reputation points
    2020-12-22T07:01:40.437+00:00

    I didn't try with "origins" wild card but I am able to fix it by creating my Web API within SharePoint IIS website so now they both share same server name which is https://myserver

    Here's how I did it:

    1. Opened IIS
    2. Right clicked on "SharePoint - 80" website and then on "Add Application"
    3. You can give some new to this new application for e.g. MyApp and also browse and select the folder where it resides
    4. Press OK and you are done

    Now I can access my Web API from within SharePoint as https://myserver/myapp/api/CFP/GetCustomerName


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.