mike_hornbeck mike_hornbeck - 1 year ago 117
ASP.NET (C#) Question

How to add cross domain support to WCF service

I'm trying to allow POST requests from my javascript app hosted at localhost:80 to a WCF REStful service hosted at a different port, but somehow it doesn't work. I've tried adding custom properties to the header, as well as adding it programatically in my service's

method but I'm still getting '405 Method not allowed' in my response. What is the proper approach here ?

This is my interface :

namespace RestService
public class RestServiceImpl : IRestServiceImpl
#region IRestServiceImpl Members

public string JSONData()
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return "Your POST request";


and the service code :

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web.Script.Services;

namespace RestService

public interface IRestServiceImpl
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "export")]
string JSONData();

And finally the config :

<?xml version="1.0"?>

<compilation debug="true" targetFramework="4.0" />
<service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
<endpoint address ="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web">

<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<behavior name="web">
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<modules runAllManagedModulesForAllRequests="true"/>
<add name="Access-Control-Allow-Origin" value="*" />


Answer Source

This worked better for me than the Web.config version:

Create a Global.asax

Add this code to the Global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download