有 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/