AJAX request for WCF with POST

Asked

Viewed 179 times

1

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

I am getting several errors with OPTIONS and POST methods that comes 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);

Implementation of 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);
                    }
            });

Error in the Fiddler:

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

Ajax error:

Xmlhttprequest cannot load localhost:70/Siteservice.svc/Validartpartner. Response to preflight request doesn’t pass access control check: No '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.

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

  • Xmlhttprequest cannot load http://localhost:70/Siteservice.svc/Validartpartner. Response to preflight request doesn’t pass access control check: No '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.

1 answer

2

First problem, it must be because you are releasing the CORS twice: once in the web config. and another in the 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>

The second problem is that this is not right

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

The method should be GET or POST.


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

Therefore, it was necessary to change the behavior for webHttp in web.config instead of Webscript

<behavior name="webHttpBehavior">
  <webHttp />
</behavior>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.