Como fazer uma requisição AJAX para um serviço WCF utilizando POST?
Estou obtendo diversos erros com métodos OPTIONS and POST que vem na mesma requisição.
Aqui esta meu código:
Contrato
[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);
Implementação do método
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>
Requisição AJAX
$.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);
}
});
Erro no Fiddler:
[Fiddler] The connection to 'localhost' failed. Error: ConnectionRefused (0x274d). System.Net.Sockets.SocketException Nenhuma conexão pôde ser feita porque a máquina de destino as recusou ativamente 127.0.0.1:70
Erro ajax:
XMLHttpRequest cannot load localhost:70/SiteService.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 502.