从Web窗体调用Weather Web Service时出现意外错误



我正试图从web表单(ASPX页面(调用天气web服务。预期的结果是带有天气预报的XML响应。然而,当我在浏览器中运行web表单时,我会收到一个错误"Application.中的服务器错误">

描述:HTTP 404。您正在查找的资源(或其依赖项之一(可能已被删除、名称已更改或暂时不可用。请检查以下URL并确保拼写正确。

请求的URL:/主页/WeatherServiceForm

版本信息:Microsoft.NET Framework版本:4.0.30319;ASP.NET版本:4.8.4075.0">

我相信我的代码中没有错误,并且只能想到错误的两个可能原因。首先是不正确的框架,其次是url路径的版本。

我已经尝试更改我正在使用的框架。从"ASP.NET核心Web应用程序->ASP.NET Web应用程序(.NET Framework(我使用的是Visual Studios 2019,它自动生成MVC代码类型。

第二url。Path="premium/v2/weather.ashx";url。路径应该是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;
}
}
}

您是否尝试过逐字逐句地请求文件名,关键是包括文件扩展名,例如:/WweatherServiceForm.aspx

请求的URL:/Home/WweatherServiceForm似乎是MVC风格的路由,但如果您使用的是.aspx,那么我希望它使用文件名。

"ASP.NET核心Web应用程序->ASP.NET Web应用程序(.NET Framework(我正在使用Visual Studios 2019,它自动生成MVC代码类型。">

上面的模板是正确的。

404表示服务器端的nor资源。

右键单击项目中的web表单,然后选择"在浏览器中查看"以运行特定页面(本例中为web表单(。

最新更新