Call WCF with AJAX

Asked

Viewed 99 times

1

I need to make the ajax call on an html page that will trigger a WCF application

WCF contract

[ServiceContract]
public interface IMailingService
{
    [OperationContract]
    ServiceRetorno<string> ValidarParceiro(string login, string senha);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ControleMailingService : IMailingService
    {
        public ServiceRetorno<string> ValidarParceiro(string login, string senha)
        {

            ServiceRetorno<string> ret = new ServiceRetorno<string>();
            try
            {
                using (MailingData data = new MailingData())
                {
                    ret.Sucesso = data.ValidarParceiro(login, senha);
                    if (!ret.Sucesso)
                        ret.Mensagem = "Usuário ou senha inválido";
                    else
                        ret.DadosRetorno = CriarToken(login);
                }
            }
            catch(Exception ex)
            {
                ret.Sucesso = false;
                ret.Mensagem = "Falha ao validar login: " + ex.Message;
            }
            return ret;
        }
}

ENDPOINT CONFIGURATION

      <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <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" />
        <endpoint binding="webHttpBinding" address="" 
          behaviorConfiguration="MailingServiceAjaxBehavior" contract="WcfVisualFix.IMailingService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="MailingServiceAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false"  minFreeMemoryPercentageToActivateService="0" />

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

CALLED AJAX

$(document).ready(function(){

$("#btnAcessar").click(function(){

 $.ajax({
type: "POST",
url: "http://visualfix.dyndns-web.com:93/MailingService.svc/ValidarParceiro",
data: { "login" : $("#txtUsuario").val(), "senha": $("#txtSenha").val() },
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: 
 function (res) {
if(res.Sucesso)
 $("#txtToken").val(res.DadosRetorno);
else
 $("#txtToken").val(res.Mensagem);
 },
error: 
 function (err) {
alert(err.responseJSON);
 }
 });

});
});

The call returns error statusCode 0.

Xmlhttprequest cannot load http://visualfix.dyndns-web.com:93/MailingService.svc/ValidarParceiro. 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 400.

Performing test by SOAP UI works correctly.

1 answer

0

  • From what I could understand, it is necessary to configure an Access Control in WCF to enable requests of different origins. But it is not clear to me whether this should be configured through ENDPOINT or in method coding. In Link2, this way: Weboperationcontext.Current.Outgoingresponse.Headers.Add("Access-Control-Allow-Origin", "*");

  • Can the request be made through AJAX? The link1 example is using Xmlhttprequest

Browser other questions tagged

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