[英]Unexpected error when calling Weather Web Service from a Web Form
我正在尝试从 web 表单(ASPX 页面)调用天气 web 服务。 预期结果是对天气预报的 XML 响应。 但是,当我在浏览器中运行 web 表单时,出现错误“'/'应用程序中的服务器错误。
描述:HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、更改名称或暂时不可用。 请查看以下 URL 并确保拼写正确。
请求的 URL:/Home/WeatherServiceForm
版本信息:Microsoft .NET 框架版本:4.0.30319; ASP.NET 版本:4.8.4075.0"
我相信我的代码没有错误,只能想到两个可能的错误原因。 首先是不正确的框架,其次是 url 路径的版本。
我试图改变我正在使用的框架。 从“ASP.NET Core Web 应用程序 - > ASP.NET Web 应用程序(.NET Framework)我使用 Visual Studios 2019 代码类型,它自动生成了 MVC 代码类型
其次 url.Path = "premium/v2/weather.ashx"; url.Path 应该是 v1 还是 v2 我不确定。
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument wsResponseXmlDoc = new XmlDocument();
//http://api.worldweatheronline.com/premium/v1/weather.ashx?key=****&q=London&format=xml&num_of_days=5
//id=jipx(spacetime0)
UriBuilder url = new UriBuilder();
url.Scheme = "http";// Same as "http://"
url.Host = "api.worldweatheronline.com";
url.Path = "premium/v2/weather.ashx";// change to v2
url.Query = "q=china&format=xml&num_of_days=5&key=******";
//Make a HTTP request to the global weather web service
wsResponseXmlDoc = MakeRequest(url.ToString());
if (wsResponseXmlDoc != null)
{
//display the XML response for user
String xmlString = wsResponseXmlDoc.InnerXml;
Response.ContentType = "text/xml";
Response.Write(xmlString);
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter(Server.MapPath("xmlweather.xml"), null);
writer.Formatting = Formatting.Indented;
wsResponseXmlDoc.Save(writer);
//You're never closing the writer, so I would expect it to keep the file open. That will stop future attempts to open the file
writer.Close();
}
else
{
Response.ContentType = "text/html";
Response.Write("<h2> error accessing web service </h2>");
}
}
public static XmlDocument MakeRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
//Set time out to 15 seconds
request.Timeout = 15 * 1000;
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
return (xmlDoc);
}
catch (Exception ex)
{
return null;
}
}
}
您是否尝试过逐字请求文件名,关键包括文件扩展名,例如:/WeatherServiceForm.aspx
请求的 URL:/Home/WeatherServiceForm 似乎是 MVC 风格的路线,但如果您使用的是.aspx,那么我希望它使用文件名。
“ASP.NET Core Web 应用程序 -> ASP.NET Web 应用程序(.NET Framework)我使用 Visual Studios 2019 并自动生成 MVC 代码。”
上面的模板是正确的。
404 表示服务器端没有资源。
右键单击项目中的 web 表单,然后选择“在浏览器中查看”以运行特定页面(本例中为 Web 表单)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.