默认情况下,启用WCF数据服务接受/返回JSON
我有一个WCF数据服务,我希望在默认情况下为所有操作返回JSON。在配置/通过服务属性中是否有可以设置的位置?您可以根据此下载添加扩展默认情况下,启用WCF数据服务接受/返回JSON,json,wcf,wcf-data-services,odata,Json,Wcf,Wcf Data Services,Odata,我有一个WCF数据服务,我希望在默认情况下为所有操作返回JSON。在配置/通过服务属性中是否有可以设置的位置?您可以根据此下载添加扩展 在代码检查是否通过URL请求JSON格式时,您仍然需要对其进行自定义。例如$format=JSON。为了通过$format标记启用JSON,如下所示: host:8038/YourService.svc/?$format=json 将此属性添加到服务声明中: [JSONPSupportBehavior] public class Service : Data
在代码检查是否通过URL请求JSON格式时,您仍然需要对其进行自定义。例如$format=JSON。为了通过$format标记启用JSON,如下所示:
host:8038/YourService.svc/?$format=json
将此属性添加到服务声明中:
[JSONPSupportBehavior]
public class Service : DataService<YourEntities>
[JSONPSupportBehavior]
公共类服务:数据服务
将此作为类添加到您的服务中:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Xml;
namespace YourNamespaceHere.Service
{
public class JSONPSupportInspector : IDispatchMessageInspector
{
// Assume utf-8, note that Data Services supports
// charset negotation, so this needs to be more
// sophisticated (and per-request) if clients will
// use multiple charsets
private static Encoding encoding = Encoding.UTF8;
#region IDispatchMessageInspector Members
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
{
if (request.Properties.ContainsKey("UriTemplateMatchResults"))
{
HttpRequestMessageProperty httpmsg = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
UriTemplateMatch match = (UriTemplateMatch)request.Properties["UriTemplateMatchResults"];
string format = match.QueryParameters["$format"];
if ("json".Equals(format, StringComparison.InvariantCultureIgnoreCase))
{
// strip out $format from the query options to avoid an error
// due to use of a reserved option (starts with "$")
match.QueryParameters.Remove("$format");
// replace the Accept header so that the Data Services runtime
// assumes the client asked for a JSON representation
httpmsg.Headers["Accept"] = "application/json";
string callback = match.QueryParameters["$callback"];
if (!string.IsNullOrEmpty(callback))
{
match.QueryParameters.Remove("$callback");
return callback;
}
}
}
return null;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
if (correlationState != null && correlationState is string)
{
// if we have a JSONP callback then buffer the response, wrap it with the
// callback call and then re-create the response message
string callback = (string)correlationState;
XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
reader.ReadStartElement();
string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64());
content = callback + "(" + content + ")";
Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content));
newreply.Properties.CopyProperties(reply.Properties);
reply = newreply;
}
}
#endregion
class Writer : BodyWriter
{
private string content;
public Writer(string content)
: base(false)
{
this.content = content;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("Binary");
byte[] buffer = JSONPSupportInspector.encoding.GetBytes(this.content);
writer.WriteBase64(buffer, 0, buffer.Length);
writer.WriteEndElement();
}
}
}
// Simply apply this attribute to a DataService-derived class to get
// JSONP support in that service
[AttributeUsage(AttributeTargets.Class)]
public class JSONPSupportBehaviorAttribute : Attribute, IServiceBehavior
{
#region IServiceBehavior Members
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.MessageInspectors.Add(new JSONPSupportInspector());
}
}
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
#endregion
}
}
使用系统;
使用System.ServiceModel;
使用System.ServiceModel.Channel;
使用System.ServiceModel.Description;
使用System.ServiceModel.Dispatcher;
使用系统文本;
使用System.Xml;
名称空间YourNamespaceHere.Service
{
公共类JSONPSuportInspector:IDispatchMessageInspector
{
//假设utf-8,请注意数据服务支持
//字符集协商,所以这需要更多
//如果客户愿意,请提供完善的(并按请求提供)
//使用多个字符集
私有静态编码=Encoding.UTF8;
#区域IDispatchMessageInspector成员
公共对象AfterReceiveRequest(参考System.ServiceModel.channel.Message请求,IClientChannel通道,InstanceContext InstanceContext)
{
if(request.Properties.ContainsKey(“UriTemplateMatchResults”))
{
HttpRequestMessageProperty httpmsg=(HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
UriTemplateMatch=(UriTemplateMatch)请求。属性[“UriTemplateMatchResults”];
字符串格式=match.QueryParameters[“$format”];
if(“json”.Equals(格式,StringComparison.InvariantCultureIgnoreCase))
{
//从查询选项中去掉$format以避免出现错误
//由于使用了保留选项(以“$”开头)
match.QueryParameters.Remove(“$format”);
//替换Accept标头,以便Data Services运行时
//假设客户端请求JSON表示
httpmsg.Headers[“Accept”]=“application/json”;
字符串回调=match.QueryParameters[“$callback”];
如果(!string.IsNullOrEmpty(回调))
{
match.QueryParameters.Remove(“$callback”);
返回回调;
}
}
}
返回null;
}
SendReply之前的公共无效(参考System.ServiceModel.Channels.Message reply,object correlationState)
{
if(correlationState!=null&&correlationState为字符串)
{
//如果我们有一个JSONP回调,那么缓冲响应,用
//回调调用,然后重新创建响应消息
字符串回调=(字符串)correlationState;
XmlDictionaryReader=reply.GetReaderAtBodyContents();
reader.ReadStartElement();
string content=jsonpsuportinspector.encoding.GetString(reader.ReadContentAsBase64());
内容=回调+”(“+content+”);
Message newreply=Message.CreateMessage(MessageVersion.None,”,新的编写器(内容));
newreply.Properties.CopyProperties(reply.Properties);
reply=newreply;
}
}
#端区
班级编剧:车身编剧
{
私有字符串内容;
公共编写器(字符串内容)
:base(假)
{
this.content=内容;
}
受保护的重写无效OnWriteByContents(XmlDictionaryWriter编写器)
{
writer.writeStarteElement(“二进制”);
byte[]buffer=jsonpsuportinspector.encoding.GetBytes(this.content);
writer.WriteBase64(缓冲区,0,缓冲区.Length);
writer.writeedelement();
}
}
}
//只需将此属性应用于DataService派生类即可获得
//该服务中的JSONP支持
[AttributeUsage(AttributeTargets.Class)]
公共类JSONPSupportBehaviorAttribute:属性,IServiceBehavior
{
#区域代理行为成员
void IServiceBehavior.AddBindingParameters(ServiceDescription ServiceDescription,ServiceHostBase ServiceHostBase,System.Collections.ObjectModel.Collection端点,System.ServiceModel.Channel.BindingParameterCollection bindingParameters)
{
}
无效IServiceBehavior.ApplyDispatchBehavior(ServiceDescription ServiceDescription,ServiceHostBase ServiceHostBase)
{
foreach(serviceHostBase.ChannelDispatchers中的ChannelDispatcher cd)
{
foreach(在cd.Endpoints中终结)
{
添加(新的JSONPSuportInspector());
}
}
}
无效IServiceBehavior.Validate(ServiceDescription ServiceDescription,ServiceHostBase ServiceHostBase)
{
}
#端区
}
}
Hi客户端是否可以为数据服务实现IDispatchMessageInspector?我创建了这个问题:您可能希望使用“application/json;odata=verbose”