c# - Wcf 发送 xml 内容类型而不是 json,

标签 c# json wcf

有 WCF 服务器和 WCF 客户端。下面是客户端代码:

[GeneratedCode("System.ServiceModel", "3.0.0.0")]
[ServiceContract(ConfigurationName = "IMyService")]
public interface IMyService
{
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, UriTemplate = "DoSmth")]
    [OperationContract(Action = "http://tempuri.org/IConfigService/SetSettings")]
    OrigamiHttpResponse<List<ErrorRecords>> DoSmth(int param);
}

public class MyService: BaseClient<IMyService>
{
    public ConfigServiceClient(AuthResult authObject) : base(authObject, null)
    {
    }

    public OrigamiHttpResponse<List<ErrorRecords>> DoSmth(int param)
    {
        return Proxy.DoSmth(param);
    }
}

public abstract class BaseClient<T> : BaseClient where T : class
{
    protected T Proxy { get; private set; }

    protected BaseClient(AuthResult authObject, IConfig config)
        : base(authObject, config)
    {
        var factory = new ChannelFactory<T>("*");

        if (factory.Endpoint == null || factory.Endpoint.Address == null)
            throw new Exception("WCF Endpoint is not configured");

        if (factory.Endpoint.Address.Uri.Scheme.ToLower() == "https")
            HttpAccess.PrepareSslRequests();

        if (_authObject != null)
        {
            var cb = new CookieBehavior(_authObject);
            factory.Endpoint.Behaviors.Add(cb);
        }

        Proxy = factory.CreateChannel();
    }
}

当我从控制台应用程序调用方法 DoSmth() 时,内容类型是 json。但我的体系结构是我正在调用代理方法,然后代理服务器充当 wcf 服务器的客户端并调用 wcf 方法,即我的 DoSmth()。在这种情况下,内容类型是 xml,我无法更改它。问题可能出在操作环境中,因为这是一个来自另一个的调用。有谁能帮忙吗?

最佳答案

这是因为您的 WCF 客户端(Proxy)正在服务方法的操作上下文中运行(其中包含有关传入请求的信息),并且覆盖了应该由传出请求使用。要解决此问题,您需要在调用时创建一个新的操作上下文范围,以便它将使用 WebInvoke/WebGet 属性中的适当属性:

public OrigamiHttpResponse<List<ErrorRecords>> DoSmth(int param)
{
    using (new OperationContextScope((IContextChannel)Proxy))
    {
        return Proxy.DoSmth(param);
    }
}

关于c# - Wcf 发送 xml 内容类型而不是 json,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27781516/

相关文章:

c# - 如何将自定义事件字符串写入 Aws cloudwatch 日志

c# - 初始化编号字符串列表的快速方法?

javascript - JSON 的二进制编码?

java - 如何从对象内部的数组中获取内部值?

wcf - 为构建 WCF 添加哪些 VS 构建工具工作负载?

.net - SCT到期后续订WCF客户端吗?

c# - 需要帮助了解 Azure Functions 中异步/等待调用中的后台任务

c# - 运行 C# .NET Winform 应用程序,该应用程序使用 SQL Server 作为数据库,仅将 .mdf 文件放置在用户 PC 上

json - 将 JSON 变量传递给 AzureDevops Release 定义

c# - NHibernate 级联删除