Activer le Service de Données WCF pour accepter/retour JSON par défaut
J'ai un Service de Données WCF que j'aimerais retour JSON par défaut pour toutes les opérations. Est-il un endroit où je peux définir que dans configuration/via les attributs du service?
usingSystem;usingSystem.ServiceModel;usingSystem.ServiceModel.Channels;usingSystem.ServiceModel.Description;usingSystem.ServiceModel.Dispatcher;usingSystem.Text;usingSystem.Xml;namespaceYourNamespaceHere.Service{publicclassJSONPSupportInspector: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 charsetsprivatestaticEncoding encoding =Encoding.UTF8;#region IDispatchMessageInspector MemberspublicobjectAfterReceiveRequest(refSystem.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;}}}returnnull;}publicvoidBeforeSendReply(refSystem.ServiceModel.Channels.Message reply,object correlationState){if(correlationState !=null&& correlationState isstring){//if we have a JSONP callback then buffer the response, wrap it with the//callback call and then re-create the response messagestring 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,"",newWriter(content));
newreply.Properties.CopyProperties(reply.Properties);
reply = newreply;}}#endregionclassWriter:BodyWriter{privatestring content;publicWriter(string content):base(false){this.content = content;}protectedoverridevoidOnWriteBodyContents(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)]publicclassJSONPSupportBehaviorAttribute:Attribute,IServiceBehavior{#region IServiceBehavior MembersvoidIServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription,ServiceHostBase serviceHostBase,System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,System.ServiceModel.Channels.BindingParameterCollection bindingParameters){}voidIServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription,ServiceHostBase serviceHostBase){foreach(ChannelDispatcher cd in serviceHostBase.ChannelDispatchers){foreach(EndpointDispatcher ed in cd.Endpoints){
ed.DispatchRuntime.MessageInspectors.Add(newJSONPSupportInspector());}}}voidIServiceBehavior.Validate(ServiceDescription serviceDescription,ServiceHostBase serviceHostBase){}#endregion}}
Salut est-il possible sur le côté client de mettre en œuvre IDispatchMessageInspector pour l'instance DataService? J'ai créer cette question: stackoverflow.com/questions/18613078/... Vous souhaiterez peut-être utiliser "application/json;odata=verbose"
Vous auriez encore besoin de le personnaliser comme le code est de la vérification pour voir si vous demandez JSON formatage à l'aide de l'URL.e.g $format=json.
Afin de permettre json via le format $balise comme ceci:
Ajouter cet attribut à votre déclaration de service:
Ajouter une classe à votre service:
Vous souhaiterez peut-être utiliser "application/json;odata=verbose"
OriginalL'auteur George
Vous pouvez ajouter une extension de ce téléchargement.
http://archive.msdn.microsoft.com/DataServicesJSONP
Vous auriez encore besoin de le personnaliser comme le code est de la vérification pour voir si vous demandez JSON formatage à l'aide de l'URL.e.g $format=json.
OriginalL'auteur SCB