场景:客户端访问WebService连接,需要返回实体类的集合。采用xml字符串的形式传输,用到了序列化和反序列化。
具体步骤及代码:
1 在WebService中定义了实体类。
[Serializable]
public class LightningStrike
{
public int ID { get;set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
public DateTime DateTime { get; set; }
public double Intensity { get; set; }
public double Slope { get; set; }
public double Error { get; set; }
public string Province { get; set; }
public string City { get; set; }
public string District { get; set; }
public static Collection<LightningStrike> GetLightningStrikes()
{
Collection<LightningStrike> lightningStrikes = new Collection<LightningStrike>();
for (int i = 0; i < 100; i++)
{
LightningStrike strike = new LightningStrike();
strike.ID = i;
strike.Longitude = 120;
strike.Latitude = 30;
strike.Intensity = 45;
strike.DateTime = DateTime.Now;
strike.Province = "浙江省";
strike.City = "杭州市";
strike.District = "上城区";
lightningStrikes.Add(strike);
}
return lightningStrikes;
}
}
2 asmx中定义了如下内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections.ObjectModel;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
namespace WebServiceApplication
{
/// <summary>
/// Summary description for WebServiceTest
/// </summary>
[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 WebServiceTest : System.Web.Services.WebService
{
[XmlInclude(typeof(LightningStrike))]
[WebMethod]
public string GetStrikesCollection()
{
//Collection<LightningStrike> strikeCollection =Serializer.DeserializerCollection<LightningStrike>(sXml, typeof(LightningStrike));
Collection<LightningStrike> strikeCollection = LightningStrike.GetLightningStrikes();
string sXml = Serializer.Serialize<Collection<LightningStrike>>(strikeCollection);
return sXml;
}
}
}
3 采用winform作为TestApp,添加了对WebService的引用。
4 需要调用localhost下面的LightningStrike失败,代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsFormsApplicationTest.localhost;
using System.Xml.Serialization;
namespace WindowsFormsApplicationTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebServiceTest cal = new WebServiceTest();
double a = 32132.321;
double b = 54334.321;
textBoxResult.Text = cal.Div(a,b).ToString();
string resultString=cal.GetStrikesCollection();
localhost.
}
}
}
问题为什么无法调用自定义实体类型?
------解决思路----------------------
顶上那一行,以及下面的命名空间声明,都会在你“跨平台”时造成无法修复的bug。
所以不要使用 xml,它太严格了,以至于你会遇到经常遇到诡异的格式问题。应该使用 json,而不是 xml。