默认情况下,启用WCF数据服务以接受/返回JSON [英] Enable WCF Data Service to accept/return JSON by default

查看:109
本文介绍了默认情况下,启用WCF数据服务以接受/返回JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF数据服务,我想默认为所有操作返回JSON.我可以在配置/通过服务属性中设置一个地方吗?

I have a WCF Data Service that I'd like to return JSON by default for all operations. Is there a place I can set that in configuration/via service attributes?

推荐答案

为了通过$ format标记启用json,如下所示:

In order to enable json via the $format tag like this:

host:8038/YourService.svc/?$format=json

将此属性添加到服务声明中:

Add this attribute to your service declaration:

[JSONPSupportBehavior]
public class Service : DataService<YourEntities>

将此作为类添加到您的服务:

Add this as a class to your service:

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
}
}

这篇关于默认情况下,启用WCF数据服务以接受/返回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆