Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have problem with ajax query, i try make post query for wcf service and this don't work.
I got next error in my browser:
xmlhttprequest cannot load "myUrl" request header field is not allowed by access-control-allow-headers
Here my project (on github)

My Service, have next code in global.asax
C#
protected void Application_BeginRequest(object sender, EventArgs e)
    {

        EnableCrossDomainAjaxCall();
    }

    private void EnableCrossDomainAjaxCall()
    {
        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");
            HttpContext.Current.Response.End();
        }
    }


Service contract
C#
[ServiceContract]
public interface IService1
{
    [OperationContract()]
    [WebInvoke(Method = "GET", UriTemplate = "/GetTestData", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    List<Data.Test> GetTestData();

    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    void AddTestData(Data.Test value);
}


And svc code
C#
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    //static data for test
    private static List<Data.Test> _data = new List<Data.Test>() { new Data.Test() { ID = 0, Name = "a" }, new Data.Test() { ID = 1, Name = "B" } };
    public List<Data.Test> GetTestData()
    {
        return _data;
    }

    public void AddTestData(Data.Test value)
    {
        _data.Add(value);
    }
}


and my query
JavaScript
function SendData() {
    var Json = { 'id': $("#id").val(), 'name': $("#name").val() };
    $.ajax({
        type: "Post",
        url: "http://localhost:10468/Service1.svc/AddTestData",
        data: JSON.stringify(Json), 
        contentType: "application/json;charset-uf8", 
        dataType: "json", 
        success: function (msg) {
        },
        error: function (err) {
        }
    });
}


I don't knowe whay it's not working. Help me please.
P.S. Sorry for my english.
Posted

 
Share this answer
 
I fix this problem.
Need add this parameters ("Origin, X-Requested-With, Content-Type, Accept") in "Access-Control-Allow-Headers"

C#
protected void Application_BeginRequest(object sender, EventArgs e)
        {
            
            EnableCrossDomainAjaxCall();
        }

        private void EnableCrossDomainAjaxCall()
        {
            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-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
 
Share this answer
 
I have this config in my service project.
My config:
XML
<configuration>

  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetframework="4.0" />
    <customerrors mode="Off" />
  </system.web>
  <system.servicemodel>
    <bindings>
      <webhttpbinding>
        <binding name="CORSWebHttpBinding" crossdomainscriptaccessenabled="True" maxreceivedmessagesize="2147483647" maxbuffersize="2147483647">
          <readerquotas maxdepth="32" maxstringcontentlength="2147483647" maxarraylength="2147483647" maxbytesperread="2147483647" maxnametablecharcount="2147483647" />
          <security mode="None">
            <transport clientcredentialtype="None" />
          </security>
        </binding>
      </webhttpbinding>
    </bindings>
    <services>
      <service name="WcfServiceHost.Service1" behaviorconfiguration="CORSServiceBehavior">
        <endpoint address="" binding="webHttpBinding" bindingconfiguration="CORSWebHttpBinding" behaviorconfiguration="EndpBehavior" contract="WcfServiceHost.IService1" />
      </service>
    </services>
    <behaviors>
      <servicebehaviors>
        <behavior name="CORSServiceBehavior">
          <servicemetadata httpgetenabled="true" />
          <servicedebug includeexceptiondetailinfaults="true" />
        </behavior>
      </servicebehaviors>
      <endpointbehaviors>
        <behavior name="EndpBehavior">
          <webhttp />
        </behavior>
      </endpointbehaviors>
    </behaviors>
    <servicehostingenvironment multiplesitebindingsenabled="true" />
    <standardendpoints>
      <webscriptendpoint>
        <standardendpoint name="" crossdomainscriptaccessenabled="true" />
      </webscriptendpoint>
    </standardendpoints>
  </system.servicemodel>
  <system.webserver>
    <httpprotocol>
      <customheaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customheaders>
    </httpprotocol>
    <modules runallmanagedmodulesforallrequests="true" />
  </system.webserver>

</configuration>
 
Share this answer
 
I find problem, this error only in chrome, ie work fine. How do it in chrome?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900