感謝您的幫助。我決定使用WCF和JSON響應來連接到我的Windows Phone 8應用程序..我沒有完全選擇WCF,它是作業的一部分,但我將使用WCF的身份驗證和授權系統中的構建與用戶憑據..我要序列化每次以JSON格式的響應,然後返回時GZIP。通過適度的測試,結果變得很安靜。如果有人想知道這是一些示例代碼(我正在使用JSON.NET):
private string GetSuppliersLite()
{
// Get the ObjectContext that is the data source for the service.
NorthwindEntities context = this.CurrentDataSource;
try
{
var suppliers = (from s in context.Suppliers
select new
{
Address = s.Address,
City = s.City,
CompanyName = s.Company_Name,
ContactName = s.Contact_Name,
ContactTitle = s.Contact_Title,
Country = s.Country,
Fax = s.Fax,
Phone = s.Phone,
PostalCode = s.Postal_Code,
Region = s.Region,
SupplierID = s.Supplier_ID,
}
).ToList();
string jsonClient = null;
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
jsonSerializer.MissingMemberHandling = MissingMemberHandling.Error;
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Error;
try
{
using (StringWriter sw = new StringWriter())
{
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
jsonSerializer.Serialize(jtw, suppliers);
}
jsonClient = sw.ToString();
}
}
catch (Exception ex)
{
ex = ex; // have a breakpoint here so can inspect exception
}
return jsonClient;
}
catch (Exception ex)
{
throw new ApplicationException(string.Format(
"An error occurred: {0}", ex.Message));
}
}
[WebGet]
public string GetSuppliersLiteZip()
{
return Zip(GetSuppliersLite());
}
private string Zip(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for compress
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();
//Transform byte[] zip data to string
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();
return sB.ToString();
}
來源
2014-02-03 15:31:18
kms
WCF本身並不意味着您必須使用XML。它可以很容易地在json(或tcp)中產生響應。 – faester
是的,但仍然這意味着它可以使用WCF返回JSON的WP8? – kms
咦? SOAP的「開銷」不適用於JSON。 SOAP的開銷不是由WCF引起的 - 它是由SOAP引起的。 –