1

我正在尝试制作一个连接到我的数据库的 web api,获取一些地理数据,然后返回一个网页将使用的 KML 内容(在谷歌地图 iframe/div 上显示信息)。

我正在使用sharpKML(我不知道这是否是正确的选择):

public class KmlController : ApiController
{
    public HttpResponseMessage Get()
    {
        Point point = new Point();
        point.Coordinate = new Vector(37.42052549, -122.0816695);

        Placemark placemark = new Placemark();
        placemark.Name = "Somewhere";
        placemark.Geometry = point;

        Kml kml = new Kml();
        kml.Feature = placemark;

        return Request.CreateResponse(HttpStatusCode.OK, kml, new XmlMediaTypeFormatter(), "application/vnd.google-earth.kml+xml");
    }
}

但是当我调用http://something.on.my.lan/api/kml我得到这个异常:

System.InvalidOperationException:“ObjectContent`1”类型无法序列化内容类型“application/vnd.google-earth.kml+xml”的响应正文;字符集=utf-8'。

我错过了什么?

解决方案

不幸的是,正如在这个答案中所说,即使我设法动态创建 KML 内容,它也不会显示在地图上,因为该 URL 必须由 Google 公开访问(用于缓存目的)。我必须改变方法。

4

2 回答 2

1

先试试这个,我想知道是否有任何对象的序列化有问题:

private string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    StringWriter textWriter = new StringWriter();

    xmlSerializer.Serialize(textWriter, toSerialize);
    return textWriter.ToString();
}


public class KmlController : ApiController
{
    public string Get()
    {
        Point point = new Point();
        point.Coordinate = new Vector(37.42052549, -122.0816695);

        Placemark placemark = new Placemark();
        placemark.Name = "Somewhere";
        placemark.Geometry = point;

        Kml kml = new Kml();
        kml.Feature = placemark;

        return SerializeObject<Kml>(kml);;
    }
}

如果它失败了,我建议你参考序列化文档,这样你就可以找到哪个对象没有正确序列化。

http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx

于 2014-05-28T16:11:24.303 回答
0

这对我有用...

    public static byte[] SerializeKml(this KmlFile kml)
    {
        var serializer = new Serializer(); 
        serializer.Serialize(kml.Root); 
        var str = serializer.Xml;

        var bytes = new byte[str.Length * sizeof(char)];
        Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    public ActionResult GetKml()
    {
        Placemark placemark = new Placemark
        {
            Geometry = new Point { Coordinate = new Vector(-13.163959, -72.545992) },
            Name = "Machu Picchu",
        };

        var kml = KmlFile.Create(placemark, false);
        var fcResult = new FileContentResult(kml.SerializeKml(), "application/vnd.google-earth.kml+xml") { FileDownloadName = "MachuPicchu.kml" };
        return fcResult;
    }
于 2015-10-05T04:00:06.377 回答