c# - WebRequest 奇怪的 NotFound 错误

标签 c# asp.net-core httpwebrequest http-status-code-404 webrequest

我有 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/

相关文章:

c# - 从列表中删除不调用 setter ?

c# - 我可以使用 .NET Core 编写 PowerShell 二进制 cmdlet 吗?

asp.net-core - identityserver 4 获取当前用户的 access_token

asp.net-mvc - ASP.NET Core 1.0 中的 AWS Elastic Beanstalk 环境变量

c# - 如何访问 MVC 3 中 Request.Form 集合中未验证的项目

c# - Twitter 登录表单中的 ui_metrics

c# - 当 XML 具有特定的根元素名称时,如何将 XML 文件正确读入集合中?

c# - 使用表达式树构建 LINQ GroupBy 查询

c# - Asp .net core在用户空闲时间后自动注销

javascript - 开发 Multi-Tenancy 应用程序,以便用户可以在同一浏览器中使用不同的选项卡在不同的组织中工作