(原因:CORS标头“ Access-Control-Allow-Origin”缺失)

时间:2019-02-12 06:16:53

标签: javascript jquery rest wcf

大家好,我无法从客户端PC获取JSON值。我创建了WCF REST服务,并将该服务添加到客户端PC上的IIS中。从客户端PC打开我的网站,此方法<触发了em> readIndicator 。但是收到了一条错误消息。我已经在web.config中添加了Access-Control-Allow-Origin。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/weightservice/WeightService.svc/GetReader. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

WCF web.Config

<?xml version="1.0"?>
<configuration>
  <appSettings>  
    <add key="BandRate" value="2400"/>  
    <add key="Parify" value="0"/>
    <add key="Port" value="COM3"/>  
    <add key="Bits" value="8"/>
    <add key="Model" value="BDI2001B"/>  
    <add key="DecimalPoint" value="0"/>  
    <add key="Output" value="BDI-2001"/>  
  </appSettings>
  <connectionStrings/>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <!--
        The <authentication> section enables configuration 
        of the security authentication mode used by 
        ASP.NET to identify an incoming user. 
    -->
    <authentication mode="Windows"/>
    <!--
        The <customErrors> section enables configuration 
        of what to do if/when an unhandled error occurs 
        during the execution of a request. Specifically, 
        it enables developers to configure html error pages 
        to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
         <error statusCode="403" redirect="NoAccess.htm" />
         <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
    -->
    <authorization>
      <allow users="*"/>
    </authorization>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <!-- 
      The system.webServer section is required for running ASP.NET AJAX under Internet
      Information Services 7.0.  It is not necessary for previous version of IIS.
  -->
  <system.webServer>
    <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>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false 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="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>
    <services>
      <service name="WCFWeightService.WeightService" behaviorConfiguration="ServiceBehavior">

        <endpoint binding="webHttpBinding" contract="WCFWeightService.IWeightService" behaviorConfiguration="web">


        </endpoint>
      </service>

    </services>

    <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>

我的网站

function readIndicator() {
    try {
        $.ajax({
            type: "GET",
            dataType: 'json',
            async: true,
            contentType: "application/x-www-form-urlencoded",
            url: 'http://localhost/weightservice/WeightService.svc/GetReader',
            success: function (data) {
                if (data != "" || data != null) {
                    console.log(data);
                    console.log(data.GetReaderResult);
                    $("#indicator").text(data.GetReaderResult);
                }
            },
            error: function (request, status, error) {
                //gmyMsgbox('Failed to perform CheckToyNameExist', 'Err');
                //err.preventDefault();
                console.log(error);
            },
        });
    } catch (err) {
        //gmyMsgbox(err.message, 'Err');
        console.log(err);
        err.preventDefault();
    }
}

客户端PC Windows XP 32位

我的电脑 Windows 10

我已经在自己的PC上尝试过了,没问题。我不知道我犯了什么错误。伙计们,可以帮助我解决这个问题。

2 个答案:

答案 0 :(得分:0)

目前,我刚刚在客户端PC浏览器上安装了“ Allow CORS:Access-Control-Allow-Origin”插件。

答案 1 :(得分:0)

我有一个解决wcf服务跨域问题的解决方案。
将global.asax文件添加到项目中,并将以下代码添加到 Begin_request 事件中。

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", "POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

请随时让我知道问题是否仍然存在。