Create Web API using CORS [Cross-Origin Resource Sharing]

This post will demonstrate you to create Web API, which can be, accessed across different domain also known as CORS (Cross-Origin Resource Sharing).

Create Visual Studio Solution.

Select Visual Studio Web Application Project.

I am going to keep name as Nilesh.WebAPISQLCORS as this Web API will call SQL Server Stored Procedure to Insert Data into SQL Table.

Select Project Type Empty and Core reference as Web API.

Click OK.

It will create Project Solution as shown in below image.

Now let’s add Controller Action.

Select Web API 2 Controller Empty

Click on Add. Now Add a Name for Controller. I am going to keep name as Employee

It will add controller class in folder as shown below

Now lets adds method for Get and Post Action

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Nilesh.WebAPISQLCORS.Controllers
{
    public class DataInfo
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string ContactNumber { get; set; }
    }
    public class EmployeeController : ApiController
    {
        string connectionString = System.Configuration.ConfigurationManager.AppSettings["SQLServerConnectionString"];

        // GET: api/New
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // POST: api/New
        [ActionName("AddEmployee")]
        [HttpPost]
        public string Post([FromBody]DataInfo value)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("spInsertEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Name", value.Name);
                cmd.Parameters.AddWithValue("@Email", value.Email);
                cmd.Parameters.AddWithValue("@ContactNumber", value.ContactNumber);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }

            return "Item successfully added.";
        }
    }
}

Note that I have already added SQLServerConnectionString Configuration in Web.Config File.

Now we need to add Web API Cors so that we can access it from Cross Origin in other words from other application.

To add CORS in Web API navigate to Manage Nuget Packages

Navigate to Browse and search for CORS. Select Microsoft.AspNet.WebAPI.Cors Package and Click on Install

It will show you changes which will update solution

Click on OK button

Next Accept License

Once you accept License it will Add Cors and update Dll Reference in Project you can check this progress in Output Window.

Now lets add Configuration for Cors in WebApiConfig.cs File

Add Below Code to Enable Cors


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

Note that to add EnableCorsAttribute you need to add reference for System.Web.Http.Cors

Also in EnableCorsAttribute Method, you can pass parameter for Specific Origin and action whom you want to allow from different origin for demo purpose I have added * which means allow all for everything , in real scenario you can specify parameter name as per your requirement

By applying this code now our WEB API is ready to access it from other origin, hit F5 to test it.

You can check Get Action Response using URL: http://localhost:47965/api/Employee
(You need to change application Port number from URL)

Now to check POST request let use Postman

Make sure you pass input parameter value and Action name in Poster as shown in below Image

Sample JSON Parameter Format


{ Name: "Nilesh Rathod", Email: "njrathod@gmail.com" , ContactNumber: "+919825899769" }

Once you enter all information in Postman Click on Sent button it will post all required information to WebAPI and create record using AddEmployee Action in SQL Server.You can also get Action response in Body Section as Shown in an Image.

Now lets host our Web API to any other location instead of localhost and can share its url to other application so that they can use it.

Note that this code is not for Production Purpose, as it has not implemented with other features.

For demonstration, I have hosted this Web API Project on Azure Environment.

I have taken Azure trial for demonstration Lets check our Azure Web APP.

Next Download Publishing Profile for Web APP (which we need to use in next step to publish application )

Next Click move to Visual Studio Web API Project and Click on Publish.

Pick Azure Publish Target and Import profile which we download in previous step.

Once you select profile, it will immediately start publishing.You can see its progress in Output Window

Next step is to check Get Request

We are able to receive response. Now let’s try Post Request using Postman

It confirms that Web API is working as per expectation on Production Environment.

SharePoint Online – How to Call Web API (Cross Origin)

Let’s see how to call Cross Origin Web API, which insert item in SQL Server Database.

Note that here key important thing is Web API, which accepts Cross Origin Request, and insert data into SQL Server. If you are not aware about how to create Web API using CORS, please check my article on How to Create WEB API using CORS.

This article will help you to call Web API using jQuery (web API insert Data into SQL Server Database)

I have created Page in Pages Library named “AddEmployeeSQL.aspx”

I have also created CustomScript named folder inside Style Library, which will hold webapi.txt – custom txt file, which includes jQuery and html content.

Content For webapi.txt File is as below.

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

<div style="font-family:Verdana;font-size:11px">
    <h3>SharePoint Online - WebAPI - SQL Insert Operation</h3>
    <div>
        <table>
            <tr>
                <td>Name : </td>
                <td>
                    <input type="text" name="txtName" class="txtName" />
                </td>
            </tr>
            <tr>
                <td>Email : </td>
                <td>
                    <input type="text" name="txtEmail" class="txtEmail" />
                </td>
            </tr>
            <tr>
                <td>Contact No: </td>
                <td>
                    <input type="text" name="txtContact" class="txtContact" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button" value="Create" id="btnSave" />
                    <div id="loadingPanel" style="color:green; font-weight:bold;display:none;">Data Saving...</div>
                </td>
            </tr>
        </table>
    </div>
</div>
<script>
    $(document).ready(function () {

        $('#btnSave').click(function () {

            var name = $('.txtName').val();
            var email = $('.txtEmail').val();
            var contact = $('.txtContact').val();

            $.post("https://d2aa8fbe-0ee0-4-231-b9ee.azurewebsites.net/api/Employee", { Name: name, Email: email, ContactNumber: contact })
                .fail(function () {
                    alert("An Error Occured while saving record.");
                })
                .done(function (data) {
                    alert("Sucess: " + data);
                });
        });
    });
</script>

Now save this code in Webapi.txt (you can give your preferred name to file) file and upload it to Custom Script folder

Next Edit AddEmployeeSQL.aspx Page and add Content Editor Web Part.

Now Edit Content Editor Web Part and assign script reference

Save Page (check in and Publish it) and we are ready to check functionality.

Fill required Information and Click on Create Button.

You can see it will create record in SQL Server Database.

Hence, we can conclude that it’s really very easy to use Cross Origin Web API and using SharePoint Online jQuery Method.