gpt4 book ai didi

c# - WCF 服务可以处理哪些数据类型?

转载 作者:行者123 更新时间:2023-11-30 21:03:36 25 4
gpt4 key购买 nike

我是 WCF 新手。以前我将 WCF 服务用于基本数据类型,如字符串、int32 等。但是当我尝试使用 BitmapImage 类时,它的测试客户端给出以下错误

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.

当我将 BitmapImage 替换为 String 时,它工作正常。这意味着我遗漏了一段代码。

为了更好地理解这里是我的代码。

WCF接口(interface)代码

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MyWcfService
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void MyMethod(MyDataContract obj);
}

[DataContract]
public class MyDataContract
{
[DataMember]
public BitmapImage MyProperty { get; set; }
}
}

WCF 服务代码

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MyWcfService
{
public class Service1 : IService1
{
public void MyMethod(MyDataContract obj)
{
//No code. It is blank.
}
}
}

Web.Config代码

  <system.serviceModel>
<services>
<service name="MyWcfService.Service1" behaviorConfiguration="MyWcfService.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="MyWcfService.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWcfService.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 -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

最佳答案

您应该在您的MyDataContract 类中添加BitmapImage 的KnownType

[KnownType(typeof(BitmapImage))]
[DataContract]
public class MyDataContract
{
[DataMember]
public BitmapImage MyProperty { get; set; }
}

这是因为字符串是原始类型而 BitmapImage 不是,所以你应该“告诉”编译器在序列化/反序列化时它会处理哪些数据类型。

关于c# - WCF 服务可以处理哪些数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771378/

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