gpt4 book ai didi

c# - WCF 方法抛出 SerializationException

转载 作者:行者123 更新时间:2023-12-04 04:56:27 27 4
gpt4 key购买 nike

所以我自己托管 WCF 服务。当我通过客户端调用我的 GetProject() 方法时,我得到一个 Unhandled CommuncationException 和一个 InnerException

"The underlying connection was closed: An unexpected error occurred on a receive."



以及它的 InnerException:

"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."



现在我知道这只是一个一般性的消息,并没有告诉我太多。所以我配置了一个服务跟踪,这就是我得到的:

at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc& rpc)System.Runtime.Serialization.SerializationException: Type 'System.FormatException' with data contract name 'FormatException:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.



所以我接受了这条消息并修改了我的代码,现在我相信我这样做是正确的。我遵循了几个教程,但我仍然在服务跟踪中不断收到此异常。

在我的 ServiceContract我有以下几点:
[OperationContract]
Project GetProject(int id);

编辑已删除 KnownTypeAttribute使用。在此处注释以反射(reflect)更改。

这是我对 Project 类及其使用的类的实现:
    [DataContract]
//[KnownType(typeof(Contact))]
//[KnownType(typeof(ProjectDetails))]
//[KnownType(typeof(CommercialEntity))]
public class Project
{
[DataMember]
public ProjectDetails details = new ProjectDetails();
[DataMember]
public List<Contact> contacts = new List<Contact>();
[DataMember]
public List<CommercialEntity> POs = new List<CommercialEntity>();
[DataMember]
public List<CommercialEntity> invoices = new List<CommercialEntity>();
[DataMember]
public List<CommercialEntity> quotes = new List<CommercialEntity>();
[DataMember]
public List<CommercialEntity> CRs = new List<CommercialEntity>();
}

[DataContract]
public class ProjectDetails
{
[DataMember]
public int projectId { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public int calYearId { get; set; }
[DataMember]
public string projectState { get; set; }
[DataMember]
public string reportTitle { get; set; }
[DataMember]
public int plantId { get; set; }
[DataMember]
public string holdNumber { get; set; }
[DataMember]
public string holdDescription { get; set; }
[DataMember]
public string remarks { get; set; }
[DataMember]
public string adminComments {get; set; }
[DataMember]
public int companyId { get; set; }
[DataMember]
public int customerId { get; set; }
[DataMember]
public string folderNumber { get; set; }
[DataMember]
public int invoicedInFull { get; set; }
[DataMember]
public int approved { get; set; }
}
}

[DataContract]
public class CommercialEntity
{
[DataMember]
public string number { get; set; }
[DataMember]
public DateTime date { get; set; }
[DataMember]
public string comments { get; set; }

public CommercialEntity(string setNumber, DateTime setDate, string setComments)
{
number = setNumber;
date = setDate;
comments = setComments;
}
}

[DataContract]
public class Contact
{
[DataMember]
public string firstName { get; set; }
[DataMember]
public string lastName { get; set; }
[DataMember]
public string emailAddress { get; set; }
[DataMember]
public string phoneNumber { get; set; }
[DataMember]
public int alert { get; set; }
[DataMember]
public int projectLead { get; set; }
[DataMember]
public int mainContact { get; set; }

public Contact(string first, string last, string email, string phone, int alrt, int projLead, int mainCntct)
{
firstName = first;
lastName = last;
emailAddress = email;
phoneNumber = phone;
alert = alrt;
projectLead = projLead;
mainContact = mainCntct;
}

public Contact() { }
}

我的理解有什么漏洞?

这是我运行客户端时看到的:

See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box.

***** Exception Text *******

System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to myInternalIP:myPort/ProjectService/ProjectService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

--- End of inner exception stack trace ---

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)

at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)

--- End of inner exception stack trace ---

at System.Net.HttpWebRequest.GetResponse()

at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

--- End of inner exception stack trace ---

Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)

at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)

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 IProjectService.GetQuerytoList(Int32 id)

at ProjectServiceClient.GetQuerytoList(Int32 id) in C:\Users\drwill\documents\visual studio 2010\Projects\ProjectBaseWCF\ProjectBase\generatedProxy.cs:line 1065
at ProjectWCFClient.MainForm.openToolStripMenuItem_Click(Object sender, EventArgs e) in C:\Users\drwill\documents\visual studio 2010\Projects\ProjectBaseWCF\ProjectBase\PBMain.cs:line 961

at ProjectWCFClient.MainForm.ProjectListBox_DoubleClick(Object sender, EventArgs e) in C:\Users\drwill\documents\visual studio 2010\Projects\ProjectBaseWCF\ProjectBase\PBMain.cs:line 55

at System.Windows.Forms.Control.OnDoubleClick(EventArgs e)

at System.Windows.Forms.ListBox.WndProc(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)



这是我的客户端配置:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IProjectService" maxReceivedMessageSize="500000000" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://192.168.0.99:9000/ProjectService/ProjectService"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IProjectService"
contract="IProjectService" name="BasicHttpBinding_IProjectService" />
</client>
</system.serviceModel>
</configuration>

这是我的服务配置:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service behaviorConfiguration="ProjectBaseWCFServiceLib.Service1Behavior" name="ProjectBaseWCFServiceLib.ProjectService">
<endpoint address="" binding="basicHttpBinding" contract="ProjectBaseWCFServiceLib.IProjectService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/ProjectBaseWCFServiceLib/Service1/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ProjectBaseWCFServiceLib.Service1Behavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above 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 -->
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

此外,我以编程方式配置我的控制台应用程序主机:
     BasicHttpBinding binding = new BasicHttpBinding();
binding.OpenTimeout = new TimeSpan(0, 10, 0);
binding.CloseTimeout = new TimeSpan(0, 10, 0);
binding.SendTimeout = new TimeSpan(0, 10, 0);
binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
binding.MaxReceivedMessageSize = 500000000;
binding.MaxBufferSize = 500000000;
binding.MaxBufferPoolSize = 500000000;

selfHost.AddServiceEndpoint(typeof(IProjectService), binding, "ProjectService");

最佳答案

好的。所以这有点晚了,但它是这样的:
System.FormatException被抛出的原因是发生了 int.Parse("0")GetProject(int id)我调用它时的方法。

所以我改变了处理 "0" 的方法案例通过调用更强大的 Convert.ToInt32("0") .

我认为这里学到的教训是你应该首先确保你正在执行的方法有效。只有到那时,您才应该开始询问 DataContractSerializer不足以序列化您的类型。

关于c# - WCF 方法抛出 SerializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16698349/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com