【问题标题】:WCF service shows empty screen on browserWCF 服务在浏览器上显示空白屏幕
【发布时间】:2016-12-24 23:06:39
【问题描述】:

我有一个测试 WCF 服务,当我在 Visual Studio 上尝试时,它工作正常,当我将链接 http://localhost:1347/Service1.svc/DoWork 粘贴到浏览器中时,它显示错误请求,浏览器为空白屏幕

加载资源失败:服务器响应状态为 400 (错误请求)

当我尝试使用 JSON 时显示 CORS 问题,我在 Web.Config 中添加了一些脚本但仍然存在错误请求的问题,WCF 有以下操作合同;

namespace WcfService1
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string DoWork();

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);


    }
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

他们的实现就在这里。

public class Service1 : IService1
    {

        public string DoWork()
        {
            return string.Format("This is DoWork()");
        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

Web.Config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>

    <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"/>
    <validation validateIntegratedModeConfiguration="false"/>




  </system.webServer>

</configuration>

JSON 调用

$(document).ready(function(){
            $.get("http://localhost:1347/Service1.svc/DoWork", function(data, status){

                alert("Data: " + data + "\nStatus: " + status);
        });

【问题讨论】:

    标签: c# json wcf cors bad-request


    【解决方案1】:

    在您的global.asax 文件中添加以下代码。这将允许preflight 请求成功完成。

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

    【讨论】:

    • 什么也没发生。 localhost:1347/Service1.svc/DoWork 这仍然在浏览器中显示错误请求
    • 你能贴出详细的错误信息吗?请参阅控制台中的网络选项卡。
    • 另一个是 XMLHttpRequest 无法加载localhost:1347/Service1.svc/DoWork。 “Access-Control-Allow-Origin”标头包含多个值“*、*”,但只允许一个值。因此不允许访问 Origin 'localhost'。
    • 如果我只将它粘贴到 ajax 中调用它会给我成功 $(document).ready(function(){ $.get("http://localhost:1347/Service1.svc", function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); 但使用方法它会显示错误的请求错误
    【解决方案2】:

    “错误请求”响应是由于 HTTP 动词不匹配造成的。 WCF 中使用 basicHttpBinding 的所有操作的 SOAP 请求使用 HTTP POST,而不是 HTTP GET。 如果要使用 HTTP GET,请使用 webHttpBinding。

    或者更好的是,使用 Web API 而不是 WCF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2019-08-08
      • 2017-03-26
      • 2016-05-02
      • 2022-07-29
      相关资源
      最近更新 更多