我有 2 个不同的 ASP.NET Core 网站:admin 和 public。 都在登台服务器和本地计算机上运行。
我向不同页面发送 GET 请求以确定不同页面的执行时间并遇到管理站点问题:本地实例和暂存中的所有 url 总是返回 404 错误:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (404) Not Found.
同时,浏览器中的相同请求正常返回 html 页面。通过 HttpWebRequest
向公共(public)站点发出的请求也始终返回 200 状态代码 (OK)。
我接受的请求代码 here .
我尝试添加来自浏览器请求的所有 header 和 cookie,但没有帮助。还尝试调试本地实例,发现请求执行时没有抛出异常。
有什么想法吗?
最佳答案
404 是通用的方式。您的链接 ( https://stackoverflow.com/a/16642279/571203 ) 中答案中提供的代码没有错误处理 - 这是一个很好的例子,说明当您盲目地从 stackoverflow 复制代码时会遇到麻烦 :)
修改后的错误处理代码应该是这样的:
string urlAddress = "http://google.com/rrr";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);
string data = null;
string errorData = null;
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
data = ReadResponse(response);
}
}
catch (WebException exception)
{
using (var response = (HttpWebResponse)exception.Response)
{
errorData = ReadResponse(response);
}
}
static string ReadResponse(HttpWebResponse response)
{
if (response.CharacterSet == null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
{
return reader.ReadToEnd();
}
}
因此,当出现异常时,您不仅会获得状态代码,还会在 errorData
变量中获得来自服务器的完整响应。
要检查的一件事是代理 - 浏览器可以使用 http 代理,而您的服务器客户端不使用。
关于c# - WebRequest 奇怪的 NotFound 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872866/