Performing CORS requests using Microsoft Web API

Wikipedia defines Cross-Origin Resource Sharing (CORS) as 

The mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests

What the Wikipedia definition neglects to mention is that CORS is only made possible by HTTP headers. When a script from http://microsoft.com executes a request to http://asp.net, this said request header will include an Origin.

What is an Origin?

An origin is defined by the scheme, host, and port of a URL. http://asp.net is not the same as www.asp.net

How can we perform CORS requests?

The simplest form of CORS is using nullipotent (An action with no associated side effects) method like GET. To demonstrate this, create a new web api project and add the following files:

Student class:

public class Student
  {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
 
      public DateTime DateofBirth { get; set; }
  }

StudentsController:

public class StudentsController : ApiController
{
    IList<Student> _students;
    private IList<Student> Students
    {
        get
        {
            if (_students == null)
            {
                _students = GetStoredStudents();
            }
            return _students;
        }
    }
    static List<Student> GetStoredStudents()
    {
        return new List<Student> { new Student { Id = 1, DateofBirth = DateTime.Now.AddYears(-20), FirstName = "Sammy", LastName = "Ageil" },
        new Student { Id = 2, DateofBirth = DateTime.Now.AddYears(-50), FirstName = "John", LastName = "Doe" },
        new Student { Id = 3, DateofBirth = DateTime.Now.AddYears(-30), FirstName = "Jane", LastName = "Doe" }
        };
    }
 
    public HttpResponseMessage Get(int id)
    {
 
        //  var t = Request.Headers;
        var response = Request.CreateResponse<Student>(Students.FirstOrDefault(x => x.Id == id));
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        return response;
    }
}

Build your project to make sure everything is Ok. Once the project is built, right click on the project, go to properties and click on Web and change the project URL to match the following screen capture:

Save your project and hit F5 to run it.

Finally, copy the next snippet into an empty html file and save it as cors.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js"></script>
</head>
 
<body>
    <script>
        $(function ()
        {
            $.ajax({
                type:'GET',
                url: 'http://localhost:22774/api/Students/1',
                crossDomain: true,
 
            }).done(function(data, status, jQxhr)
            {
                console.log(data.Id);
                
            })
            .fail(function (jQxhr, status) {
                alert(status);
            });
           
        });
    </script>
</body>
</html>

You can either run the file directly from a browser (I'm using firefox with firebug installed) or save it to your into C:\inetpub\wwwroot\ then browse it using http://localhost/cors.html.

Here is my console window when I browse the cors.html

Next time we will implement Preflighted CORS where we can edit resources instead of only getting them from the server.

Comments (4) -

James Warden 3/17/2014 6:57:19 AM

Hey Sammy,
Thanks, Thanks too easy now.
Are you coming to this year conference in San Francisco?

Hi James,

You welcome, I don't have any plans set for this year. It all depends on the schedule Smile

Can you publish the code?

Which code are you looking for? All code used is already posted in the body of this blog.

Add comment