Λοιπόν, αν κατάλαβα καλά τί υποννοεί ο spaceman, λέει ότι αν φτιάξεις ένα κλασσικό asmx web service, το μόνο που χρειάζεται από την πλευρά του service για να επιστρέψει Json είναι να βάλεις το ScriptService attribute στην κλάση, το ScriptMethod attribute στη μέθοδο και να ορίσεις ως ResponseFormat το Json - χωρίς μετατροπές με το χέρι. Έτσι το service που είχα γράψει νωρίτερα γίνεται:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod,ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=true)]
public List<CustomerDetails> GetCustomers()
{
using (var dbContext = new AdventureWorksEntities())
{
var customers = (from customer in dbContext.Customers
where customer.CustomerType == "I"
select new CustomerDetails
{
CustomerID = customer.CustomerID,
AccountNumber = customer.AccountNumber
}).Take(5);
var list = customers.ToList();
return list;
}
}
}
Το κομμάτι σε bold διαφέρει από αυτά που έγραφαν τα posts στα οποία παραπέμπει ο spaceman. Τα posts αναφέρουν ότι υπάρχει vulnerability όταν καλείς Json arrays με GET, αυτό όμως δεν ισχύει όταν χρησιμοποιείς ASMΧ γιατί δεν σου επιστρέφει γυμνό array.
O client όμως θα πρέπει να ορίσει το Json στο Content-Type header. Για παράδειγμα, ένας C# client θα πρέπει να κάνει το παρακάτω:
WebClient client=new WebClient();
client.Headers["Content-Type"] = "application/json; charset=utf-8";
var data=client.DownloadString(@"http://localhost/WcfJsonTest/WebService1.asmx/GetCustomers");
Console.Write(data);
Το αποτέλεσμα είναι
{"d":[{"__type":"WcfJsonTest.CustomerDetails","CustomerID":11000,"AccountNumber":"AW00011000"},{"__type":"WcfJsonTest.CustomerDetails","CustomerID":11001,"AccountNumber":"AW00011001"},{"__type":"WcfJsonTest.CustomerDetails","CustomerID":11002,"AccountNumber":"AW00011002"},{"__type":"WcfJsonTest.CustomerDetails","CustomerID":11003,"AccountNumber":"AW00011003"},{"__type":"WcfJsonTest.CustomerDetails","CustomerID":11004,"AccountNumber":"AW00011004"}]}
Όπως βλέπουμε, το array περικλείεται στο d property κι έτσι δεν υπάρχει πρόβλημα.
Αυτό εννοούσες spaceman?
Παναγιώτης Καναβός, Freelancer
Twitter: http://www.twitter.com/pkanavos