Tengo un Servicio de datos WCF que me gustaría devolver JSON de forma predeterminada para todas las operaciones. ¿Hay algún lugar que pueda establecer en la configuración/a través de los atributos del servicio?Habilitar el Servicio de datos WCF para aceptar/devolver JSON de forma predeterminada
14
A
Respuesta
0
Puede agregar una extensión según esta descarga.
http://archive.msdn.microsoft.com/DataServicesJSONP
usted todavía necesita para personalizarlo como el código está comprobando para ver si está solicitando para el formato JSON mediante el formato URL.e.g $ = JSON.
7
A fin de que JSON a través de la etiqueta de formato $ como esto:
host:8038/YourService.svc/?$format=json
Añadir este atributo a su declaración de servicio:
[JSONPSupportBehavior]
public class Service : DataService<YourEntities>
Añadir esto como una clase a su servicio:
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
}
}
Cuestiones relacionadas
- 1. Reemplazar la serialización JSON predeterminada de WCF
- 2. Habilitar SSL para mi servicio WCF
- 3. WCF REST Servicio JSON Publicar datos
- 4. WCF servicio JSON devuelto XML de Falla
- 5. Consumir JSON en el método de servicio WCF
- 6. WCF Servicio de datos Manejo de errores
- 7. Inyectando datos a un servicio de WCF
- 8. Servicio WCF para devolver fallas con formato JSON
- 9. Utilizando el servicio de datos REST WCF como fuente de datos para servicios de informes SQL
- 10. Conservación de tipos polimórficos en un servicio WCF utilizando JSON
- 11. ¿Cómo autentico un servicio de datos WCF?
- 12. Serialización de cadena JSON para que coincida con el Parámetro de función de servicio WCF
- 13. ¿Cómo puedo habilitar el registro de WCF para que se escribe a una base de datos?
- 14. Transferir gran cantidad de datos en el servicio WCF
- 15. Django-tastypie. Salida en JSON al navegador de forma predeterminada
- 16. Devolver datos no JSON, no XML en el servicio WCF REST
- 17. WCF ¿Cómo habilitar los metadatos?
- 18. transparente de descompresión GZIP de datos post para WCF Servicio Resto
- 19. Deserialización WCF JSON genérica
- 20. Descarga simultánea de datos JSON desde servicio (s) remoto
- 21. Longitud de datos con Entity Framework (para validar longitudes de datos en un servicio WCF)
- 22. El servicio web WCF falla al recibir datos grandes
- 23. Documentación de servicio WCF
- 24. Pasar credenciales de un servicio wcf a otro servicio wcf
- 25. Servicio de dominio vs Servicio WCF?
- 26. Datos de POST al Servicio WCF de WP7
- 27. ¿Cómo activar nativamente JSONP para el servicio WCF existente?
- 28. wcf json web service
- 29. WCF BodyStyle WrappedRequest no funciona para el param entrante de JSON?
- 30. Anotaciones de datos en contratos de servicio WCF
¿Es posible en el lado del cliente implementar IDispatchMessageInspector para DataService? Creo esta pregunta: http://stackoverflow.com/questions/18613078/c-sharp-implement-iclientmessageinspector-in-wcf-data-service – VAAA
Es posible que desee utilizar "application/json; odata = verbose" – wilsjd