引用我创建的 WCF 服务时出错

如何解决引用我创建的 WCF 服务时出错

我对 WCF 比较陌生,所以我在 web.config 方面遇到了困难。

我在 IIS10 上创建了 WCF 服务。这是我的 web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,EntityFramework,Version=6.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration,visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <system.web>
    <customErrors mode="Off" />
    <compilation targetFramework="4.0" debug="true">
      <assemblies>
        <add assembly="System.Data.Entity,Version=4.0.0.0,PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="DefaultCache" duration="60" varyByParam="none" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    <authentication mode="Windows" />
  </system.web>

  <system.serviceModel>
    <services>
      <service name="FileStorageService.FileService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="FileStorageService.IFileService" />

        <!--<endpoint address="mex"  
                  binding="mexHttpsBinding"  
                  contract="IMetadataExchange" />-->
      </service>
    </services>

    <bindings>
      <basicHttpBinding>
        <binding name="basicHttpBindingConfiguration">
          <security mode="Transport">
            <transport clientCredentialType="Basic" proxyCredentialType="None" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information,set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" />
          <!-- 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>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>


  <system.webServer>
    <httpErrors errorMode="Detailed" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <connectionStrings>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

我可以引用 api,但是当我尝试使用它时收到此消息:

服务器堆栈跟踪:在 System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(消息 回复,MessageFault 故障,字符串操作,MessageVersion 版本, FaultConverter faultConverter) 在 System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime 操作,ProxyRpc& rpc) 在 System.ServiceModel.Channels.ServiceChannel.Call(字符串动作, Boolean oneway,ProxyOperationRuntime 操作,Object[] ins,Object[] outs,TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall、ProxyOperationRuntime 操作)在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage 留言)

在 [0] 处重新抛出异常:在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg) 在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,Int32 类型)在 PpsTransactionFile.MyFileServiceReference.IFileService.DownloadPpsZipFile(DownloadFileRequest 下载文件请求)在 PpsTransactionFile.MyFileServiceReference.FileServiceClient.DownloadPpsZipFile(DownloadFileRequest downloadFileRequest) 在 D:\Source\Sub\Web 项目\WebStorageApps\PpsTransactionFile\Service References\MyFileServiceReference\Reference.cs:line 493 at PpsTransactionFile.download.DownloadFile.DownloadPpsZipFile(FileParms fileParms) 在 D:\Source\Sub\Web Projects\WebStorageApps\PpsTransactionFile\download\DownloadFile.cs:line 155

我的代码:

public static Status DownloadPpsTransactionFile(FileParms fileParms)
{
  var client = new FileServiceClient();

  try
  {
    var downloadstatus = new Status();
    downloadstatus.ProgramSendType = fileParms.SendGet;

    client.ClientCredentials.UserName.UserName = "xxxxxx";
    client.ClientCredentials.UserName.Password = "xxxxxxxxxxx";
    var trucks = fileParms.Trucks.Split(Convert.ToChar(","));

    foreach (var truck in trucks)
    {
      int trk;
      if (!int.TryParse(truck,out trk))
      {
        continue;
      }

      var downloadrequest = new DownloadFileRequest();
      downloadrequest.CompanyCode = fileParms.CompanyCode;
      downloadrequest.FileType = 1;
      downloadrequest.TruckNumber = trk;
      DownloadFileResponse download;

      do
      {
        download = client.DownloadPpsTransactionFile(downloadrequest);

当我调用 wfc 方法时,它在最后一行失败。我似乎无法让 IIS 设置和 web.config 正常工作。

我在 IIS 上的设置:

enter image description here

我做错了什么?

客户端配置

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IFileService">
          <security mode="Transport">
            <transport clientCredentialType="Basic" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://SOMEDOMAIN.COM/api/fileservice/FileService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileService"
        contract="MyFileServiceReference.IFileService" name="BasicHttpBinding_IFileService" />
    </client>
  </system.serviceModel>

</configuration>

附加信息

我在事件查看器中找到了这个。我目前正在研究它以了解其含义。

FailedRequestTracing 模块未能将缓冲事件写入日志 匹配失败定义的请求的文件。不会有日志 直到此条件得到纠正为止。问题发生在 在过去 5 分钟内至少 1 次。数据是错误。

解决方法

这不是我的答案,但我不能将其作为评论发布。这是显示异常的更简洁的方式,它为您提供了 D:\Source\Sub\Web Projects\WebStorageApps\PpsTransactionFile\download\DownloadFile.cs:line 155 中的确切行号。它还表明异常已rethrown 暗示故障已被理解,因此您可以在那里开始调查:

Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply,MessageFault fault,String action,MessageVersion version,FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation,ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action,Boolean oneway,ProxyOperationRuntime operation,Object[] ins,Object[] outs,TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,Int32 type)
at PpsTransactionFile.MyFileServiceReference.IFileService.DownloadPpsZipFile(DownloadFileRequest downloadFileRequest)

at PpsTransactionFile.MyFileServiceReference.FileServiceClient.DownloadPpsZipFile(DownloadFileRequest downloadFileRequest)
in D:\Source\Sub\Web Projects\WebStorageApps\PpsTransactionFile\Service References\MyFileServiceReference\Reference.cs:line 493

at PpsTransactionFile.download.DownloadFile.DownloadPpsZipFile(FileParms fileParms)
in D:\Source\Sub\Web Projects\WebStorageApps\PpsTransactionFile\download\DownloadFile.cs:line 155

也可能只是一个错字,因为我注意到您在客户端端点配置中拼错了:<endpoint address="https://SOMEDOMIAN.COM ...,我想它应该是 <endpoint address="https://SOMEDOMAIN.COM...(注意“IA”而不是“AI”在域中)。

,

我无法将其作为评论发布,但我建议您在堆栈跟踪中找到异常消息。它可能会说明未对响应进行反序列化的原因。

如果这没有帮助,我会尝试使用 Wireshark 或日志代理来跟踪并查看哪些服务器回复了您的请求。

,

您似乎一直在遵循本指南:

https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-configure-an-iis-hosted-wcf-service-with-ssl

如果您按照他们的示例进行设置,您的代码是否有效?

<?xml version="1.0"?>  
<configuration>  
  
  <system.web>  
    <compilation debug="true" targetFramework="4.0" />  
  </system.web>  
  <system.serviceModel>  
    <services>  
      <service name="MySecureWCFService.Service1">  
        <endpoint address=""  
                  binding="basicHttpBinding"  
                  bindingConfiguration="secureHttpBinding"  
                  contract="MySecureWCFService.IService1"/>  
  
        <endpoint address="mex"  
                  binding="mexHttpsBinding"  
                  contract="IMetadataExchange" />  
      </service>  
    </services>  
    <bindings>  
      <basicHttpBinding>  
        <binding name="secureHttpBinding">  
          <security mode="Transport">  
            <transport clientCredentialType="None"/>  
          </security>  
        </binding>  
      </basicHttpBinding>  
    </bindings>  
    <behaviors>  
      <serviceBehaviors>  
        <behavior>  
          <!-- To avoid disclosing metadata information,set the value below to false and remove the metadata endpoint above before deployment -->  
          <serviceMetadata 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>  
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  </system.serviceModel>  
  <system.webServer>  
    <modules runAllManagedModulesForAllRequests="true"/>  
  </system.webServer>  
  
</configuration>

鉴于错误:

FailedRequestTracing 模块未能将缓冲事件写入日志 匹配失败定义的请求的文件。不会有日志 直到此条件得到纠正为止。问题发生在 在过去 5 分钟内至少 1 次。数据是错误。

在此处查看配置:

https://docs.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis-85

我还建议您从简单开始:创建一个可以工作的基本 WCF Web HTTP 服务,然后进行修改。如果您还没有尝试过,这可能会容易得多。

控制台示例:

Service.cs:

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;

namespace Microsoft.ServiceModel.Samples.BasicWebProgramming
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }
    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service),new Uri("http://localhost:8000/"));
            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService),new WebHttpBinding(),"");
                host.Open();
                using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(),"http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                    IService channel = cf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                    s = channel.EchoWithGet("Hello,world");
                    Console.WriteLine("   Output: {0}",s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello,world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
                    s = channel.EchoWithPost("Hello,s);
                    Console.WriteLine("");
                }

                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();

                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}",cex.Message);
                host.Abort();
            }
        }
    }
}

https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-a-basic-wcf-web-http-service

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-