CORS support in ASP.NET Web APIs - RC version

This sample shows how another way to enable CORS (Cross-Origin Resource Sharing) in an ASP.NET Web API project, both on a global level (using a message handler) or on a per-action basis (using a filter and an action selector).

C# (1.4 MB)
5 Star
5,325 times
Add to favorites
E-mail Twitter Digg Facebook

Solution explorer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;

namespace PerActionCORS_RC.Filters
    public class EnableCorsAttribute : ActionFilterAttribute
        const string Origin = "Origin";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            if (actionExecutedContext.Request.Headers.Contains(Origin))
                string originHeader = actionExecutedContext.Request.Headers.GetValues(Origin).FirstOrDefault();
                if (!string.IsNullOrEmpty(originHeader))
                    actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeader);