Meh*_*ari 10
我建议你考虑使用HTTP Handler而不是ASP.NET页面.它将更清洁,更高效.只需在项目中添加"Generic Handler"类型的新项目,并考虑将代码移动到其ProcessRequest方法中.不过,一般方法都很好.
顺便说一下,除非你明确地将.kml文件映射到ASP.NET处理程序,否则它无论如何都不会运行.我建议使用默认.ashx扩展名并添加Content-DispositionHTTP标头来设置客户端的文件名:
Response.AddHeader("Content-Disposition", "attachment; filename=File.kml");
Run Code Online (Sandbox Code Playgroud)
另外,请注意您应该在将任何内容发送到客户端之前设置标题内容,因此您应该移动设置Content-Type并在其他内容之前添加标题.
完整解决方案(来自OP):
我是这样做的:
\\myDevServer\...\InetPub\KMLInternet Information Services (IIS) Manager在DEV服务器上打开KML文件夹,然后选择PropertiesHTTP Headers选项卡MIME types按钮NewOK两次返回HTTP Headers选项卡KML文件夹设置为ASP.NET应用程序(可能是可选的,具体取决于服务器的设置方式)
Directory选项卡Create按钮Application name字段随设置变为活动状态KMLOK,返回主IIS管理器窗口Empty Web SiteC#\\myDevServer\...\InetPub\KML\Solution Explorer
New ItemGeneric Handler从Visual Studio installed templates窗口中选择MelroseVista.ashx)Visual C#OK//
using System;
using System.Web;
using System.Xml;
public class Handler : IHttpHandler
{
public void ProcessRequest( HttpContext context)
{
context.Response.ContentType = "application/vnd.google-earth.kml+xml";
context.Response.AddHeader("Content-Disposition", "attachment; filename=MelroseVista.kml");
XmlTextWriter kml = new XmlTextWriter(context.Response.OutputStream, System.Text.Encoding.UTF8);
kml.Formatting = Formatting.Indented;
kml.Indentation = 3;
kml.WriteStartDocument();
kml.WriteStartElement("kml", "http://www.opengis.net/kml/2.2");
kml.WriteStartElement("Placemark");
kml.WriteElementString("name", "Melrose Vista FL");
kml.WriteElementString("description", "A nice little town");
kml.WriteStartElement("Point");
kml.WriteElementString("coordinates", "-80.18451400000000000000,26.08816400000000000000,0");
kml.WriteEndElement(); // <Point>
kml.WriteEndElement(); // <Placemark>
kml.WriteEndDocument(); // <kml>
kml.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
open或者save生成的KML文件.open这样做,你应该让GoogleEarth自己启动并缩放到佛罗里达州东部的图钉save这样,您应该在文件中看到以下内容\
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Melrose Vista FL</name>
<description>A nice little town</description>
<Point>
<coordinates>-80.18451400000000000000,26.08816400000000000000,0</coordinates>
</Point>
</Placemark>
</kml>
Run Code Online (Sandbox Code Playgroud)
注意:XmlTextWriter这里工作得很好.但是,XMLDocument对于较大的KML文件,我认为看起来更有希望,因为您可以在将其推送给用户之前在内存中对其进行操作.例如,如果您希望相同的点出现在GoogleEarth位置树的多个文件夹中.