Principales respuestas
como configurar WCF para que soporte JSON

Pregunta
-
Hola, tengo implementados unos servicios WCF, y quisiera consumirlos desde Jquery con JSON.
Que tengo que configurar para hacerlo? No se que poner en el web.config. Estoy usando VS2010 y Framework 4.
Tengo definida una interfaz IMobile.cs y despues el archivo Mobile.svc donde tengo las funciones.
Muchas gracias por la ayuda
Respuestas
-
Hola revisa el siguiente link allí se muestra como consumir servicios WCF desde el cliente mendiante el uso de Jquery. Aunque también lo podrias hacer usando ASP.NET AJAX library y te resultaría más fácil.
Por ejemplo:
Tengo la siguiente ASPX.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EjemploSerializacion.aspx.cs" Inherits="AJaxLib_RegClassInerz.EjemploSerializacion" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script type="text/javascript"> var ServiceProxy; function pageLoad() { ServiceProxy = new ServiceSample(); ServiceProxy.set_defaultSucceededCallback(ServiceCallSuccess); ServiceProxy.set_defaultFailedCallback(OnErrorCallback); } function OnErrorCallback(error) { alert(error._message); } function ServiceCallSuccess(result, userContext, methodName) { var resultAJAX = document.all.Result; if (result.length > 1 && typeof (result) != "string") { for (var i = 0; i < result.length; i++) { resultAJAX.innerHTML += result[i].FirstName + "<br/>"; } } else if (result.FirstName) resultAJAX.innerHTML += result.FirstName +"<br/>"; else resultAJAX.innerHTML += result + " form " + methodName + "<br/>"; } function SayHello() { var person = new AJaxLib_RegClassInerz.Person(); person.Id = 10; person.FirstName = "Armando"; person.HappyDay = "\/Date(" + Date.parse("10/04/2010") + ")\/"; ServiceProxy.SayHello(person); } function GetPerson() { ServiceProxy.GetPerson(3); } function GetPersons() { ServiceProxy.GetPersons(); } function GetPersonsByDateTiem() { ServiceProxy.GetPersonsByDateTime("\/Date(" + Date.parse("01/04/1990") + ")\/", "\/Date(" + Date.parse("01/04/2010") + ")\/"); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/ServiceSample.svc" /> </Services> </asp:ScriptManager> <br/> <asp:Button ID="BtGetPerson" runat="server" Text="Say Hello" OnClientClick="javascript:SayHello(); return false;" /> <br /> <asp:Button ID="Button1" runat="server" Text="Get Person by Id" OnClientClick="javascript:GetPerson(); return false;" /> <br /> <asp:Button ID="Button2" runat="server" Text="Get all Persons" OnClientClick="javascript:GetPersons(); return false;" /> <br /> <asp:Button ID="Button3" runat="server" Text="Get all Persons between a range datatime" OnClientClick="javascript:GetPersonsByDateTiem(); return false;" /> <div id="Result"> </div> <asp:MultiView ID="MultiView1" runat="server"> <asp:View> <label title="algo"></label> </asp:View> </asp:MultiView> </form> </body> </html>
Tengo el siguiente servicio WCF
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; namespace AJaxLib_RegClassInerz { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class ServiceSample { List<Person> persons = new List<Person>(){ new Person { Id = 1, FirstName = "Felipe", HappyDay = DateTime.Now.AddDays(-10000) }, new Person { Id = 2, FirstName = "Antonio", HappyDay = DateTime.Now.AddDays(-20000) }, new Person { Id = 3, FirstName = "Hernando", HappyDay = DateTime.Now.AddDays(-30000) }, new Person { Id = 4, FirstName = "Jose", HappyDay = DateTime.Now.AddDays(-40000) }}; // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) // To create an operation that returns XML, // add [WebGet(ResponseFormat=WebMessageFormat.Xml)], // and include the following line in the operation body: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] public string SayHello(Person person) { StringBuilder sb = new StringBuilder(); sb.Append("Hello " + person.FirstName); TimeSpan ts = person.HappyDay - DateTime.Now; sb.Append("\nYou have " + ts.Days / 365 + " years old"); sb.Append("\nYou're Id is " + person.Id); return sb.ToString(); } [OperationContract] public List<Person> GetPersons() { return persons; } [OperationContract] public Person GetPerson(int id = 1) { var obj = persons.SingleOrDefault(p => p.Id == 1); return obj; } [OperationContract] public List<Person> GetPersonsByDateTime(DateTime dateTime1, DateTime dateTime2) { var pers = persons.Where(p => p.HappyDay >= dateTime1 && p.HappyDay <= dateTime2); return pers.ToList(); } // Add more operations here and mark them with [OperationContract] } [DataContract] public class Person { int _id; [DataMember] public int Id { get { return _id; } set { _id = value; } } string _firstName; [DataMember] public string FirstName { get { return _firstName; } set { _firstName = value; } } DateTime _happyDay; [DataMember] public DateTime HappyDay { get { return _happyDay; } set { _happyDay = value; } } } }
Como verás allí la compatibilidad con ASP.NET ya te permite serializar los objetos tipo DataContract y objetern respuesta de los OperationContract de forma muy fácil y entendible.
Saludos
Custom Control Silverlight
"Blog Ingphillip's Prog: TODO WEB
New Post System.Reflection- Propuesto como respuesta Felipe Sotelo S domingo, 17 de abril de 2011 4:40
- Marcado como respuesta Eduardo PorteschellerModerator martes, 26 de julio de 2011 17:23