AJAX request for WCF with POST

0

How to make an AJAX request for a WCF service using POST?

I'm getting several errors with OPTIONS and POST methods that come in the same request.

Here is my code:

Contract

[OperationContract]
        //[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string ValidarParceiro(string login, string senha);
        [WebInvoke(Method = "OPTIONS")]
        string ValidarParceiroCors(string login, string senha);

Implementing the method

public string ValidarParceiro(string login, string senha)
        {
            string ret = "";
            try
            {
                login = HttpUtility.UrlDecode(login, Encoding.Default);
                senha = HttpUtility.UrlDecode(senha, Encoding.Default);

                ret = "OK";

                //using (MailingData data = new MailingData())
                //{
                //    if (!data.ValidarParceiro(login, senha))
                //        ret = "Usuário ou senha inválido";
                //    else
                //        ret = CriarToken(login);
                //}
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.Message, ex);
                return ex.ToString();
            }
            return ret;
        }



        public string ValidarParceiroCors(string login, string senha)
        {
            return null;
        }

GLOBAL.ASAX

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", "Authorization, Origin, Content-Type, Accept, X-Requested-With");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

WEB.CONFIG

<system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>

    <behaviors>
      <endpointBehaviors>
        <behavior name="WebScriptBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="mex">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />

    <bindings>
      <basicHttpBinding>
        <binding name="MailingService_Endpoint" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
            maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="WcfVisualFix.MailingService">
        <endpoint binding="basicHttpBinding" bindingConfiguration="MailingService_Endpoint"
          name="MailingService_Endpoint" contract="WcfVisualFix.IMailingService" />
      </service>
      <service behaviorConfiguration="mex" name="WcfVisualFix.SiteService">
        <endpoint address="" behaviorConfiguration="WebScriptBehavior"
          binding="webHttpBinding" contract="WcfVisualFix.ISiteService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

AJAX Request

$.ajax({
                url: "http://localhost:70/SiteService.svc/ValidarParceiro",
                type: "POST",
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify({ login: $("#txtLogin").val(), senha: $("#txtSenha").val() }),
                dataType: "json",
                success:
                    function (res) {
                        $("#txtToken").val(res.d);
                    },
                error:
                    function (err) {
                        alert(err.status);
                    }
            });

Fiddler error:

  

[Fiddler] The connection to 'localhost' failed. Error: ConnectionRefused (0x274d). System.Net.Sockets.SocketException No connection could be made because the target machine actively refused them 127.0.0.1:70

Error ajax:

  

XMLHttpRequest can not load localhost: 70 / SiteService.svc / ValidatePartner. Response to preflight request does not pass access control check: In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 502.

    
asked by anonymous 03.12.2016 / 18:55

1 answer

2

First problem, it must be because you are releasing CORS twice: one in web.config and one in global.asax . Try removing the following snippet from web.config

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Max-Age" value="1728000" />
  </customHeaders>
</httpProtocol>

Second problem is that this is not right

[WebInvoke(Method = "OPTIONS")]
string ValidarParceiroCors(string login, string senha);

The method should be GET or POST .

Other important information: methods have two parameters. With POST, it is not possible to serialize two parameters.

So it was necessary to change the web.config behavior to webHttp instead of WebScript

<behavior name="webHttpBehavior">
  <webHttp />
</behavior>
    
03.12.2016 / 21:12