CORS in WCF: web.config entries don't help (equivalent?) Global.asax approach works! What for?
I have a WCF Restful service that is being used by JQuery (via chrome). I encountered Cross-Origin issue with POST method and tried to solve it. Everything works fine when I added the Global.asax project and intercepted OPTION requests and responded positively, as in the below code:
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", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Things work as expected with the above code. However, this one below (in the web.config file) which I thought would do the same does not work
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
Below is a description of the error in chrome:
Failed to load resource: server responded with status 405 (Method not allowed) Index.html: 1 XMLHttpRequest cannot load http: // localhost: 61481 / ServiceRest.svc / CreateUser . Invalid status HTTP code 405 Index.html: 1 Uncaught SyntaxError: Unexpected token o
I am really interested in what I am doing wrong and am trying to fill the gap in my understanding about this! Any help would be greatly appreciated. thanks in advance
Additional information: The service definition looks like this:
[OperationContract]
[WebInvoke(UriTemplate = "/CreateUser", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
int CreateUser(UserData user);
JQuery looks like this
$.ajax({
type: "POST",
url: serviceUrl,
data: JSON.stringify( {
"Password" : "String content",
"UserID" : "String content",
"UserName" : "String content",
"UserRole" : "String content"
}),
contentType: "application/json",
dataType: "json",
success: OnSuccess,
error: OnError
});
source to share
No one has answered this question yet
Check out similar questions: