[英]Web Service C# ASP.NET cannot make requests
我在一個proyect中,當用戶在文本框中書寫時,我必須用Web服務請求的數據填充文本框(好像它是一個選擇控件)。
Web服務是在相同的解決方案中開發的。
問題是,當我從客戶端發出請求時,它拋出了我:
"Failed to load http://.../wsConsultaAfiliados.asmx: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我搜索了一會兒,我讀到這是CORS的問題。 但是,我不明白為什么。 我正在從同一域中的客戶端向Web服務請求數據。
對於我搜索的內容,我了解到當您將數據從X域發送到Y域時,CORS是出於安全原因。
這是我第一次使用Web服務,而我對應該遵循的方案有些困惑。
添加代碼
public class wsConsultaAfiliados : System.Web.Services.WebService
{
/// <summary>
/// Busca una lista de Afiliados que coincidan con los parámetros de entrada. Devuele DataTable.
/// </summary>
/// <returns></returns>
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public DataTable ConsultarAfiliados(string oPrefixText)
{
var listaAfiliados = GetAfiliados(oPrefixText);
return listaAfiliados;
}
/// <summary>
/// Devuelve un DataTable con Codigo y Nombre del afiliado.
/// </summary>
/// <param name="oPrefixText"></param>
/// <returns></returns>
public DataTable GetAfiliados(string oPrefixText)
{
negPrevision neg = new negPrevision();
return neg.obtenerAfiliadosPorNombre(oPrefixText);
}
}
這是來自Web服務的代碼。 它向邏輯層請求數據。
像這樣更新您的web.config以允許每個請求
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
對於IIS 7.5+和Rewrite 2.0,您可以使用
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
</customHeaders>
</httpProtocol>
<rewrite>
<outboundRules>
<clear />
<rule name="AddCrossDomainHeader">
<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="true">
<add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?domain1\.com|(.+\.)?domain2\.com|(.+\.)?domain3\.com))" />
</conditions>
<action type="Rewrite" value="{C:0}" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.