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.

Leave a comment