从另一个 C# Web 窗体应用程序调用 C# Web API 时出现 404

本文关键字:Web API 应用程序 另一个 窗体 调用 | 更新日期: 2023-09-27 18:36:22

我创建了一个简单的 web api,当我从 IE 访问它时,Web api 返回的正是我预期的。但是,现在我尝试使用 httpclient 从 Web 表单应用程序访问相同的 Web api。但是现在我收到404错误。但是 api 似乎有效,因为我在使用浏览器时确实会收到结果。知道出了什么问题吗?这是代码:

 HttpClientHandler handler = new HttpClientHandler()
 {
     UseDefaultCredentials = true
 };
 HttpClient client = new HttpClient(handler);
 client.BaseAddress = new Uri("http://server/appdir");
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 HttpResponseMessage response = client.GetAsync("/api/environment").Result;

从另一个 C# Web 窗体应用程序调用 C# Web API 时出现 404

这是有效的代码。

 HttpClientHandler handler = new HttpClientHandler()
 {
     UseDefaultCredentials = true
 };
 HttpClient client = new HttpClient(handler);
 client.BaseAddress = new Uri("http://eetmws10v");
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 HttpResponseMessage response = client.GetAsync("/aim2/api/environment").Result;

哇。这个周末我遇到了同样的错误,我无法想象问题的原因有多脆弱。

这是对我有用的:

string _baseAddress = "http://localhost/webapi/";
string controllerURL = "api/School";
client.BaseAddress = new Uri(_baseAddress);
string result = client.GetStringAsync("controllerURL").Result.ToString();

导致 404 错误的 _baseAddress 和控制器 URL 的组合如下:

string _baseAddress = "http://localhost/webapi/";
string controllerURL = "/api/School";

string _baseAddress = "http://localhost/webapi";
string controllerURL = "api/School";

string _baseAddress = "http://localhost/webapi";
string controllerURL = "/api/School";

我真诚地希望尽快做一些事情来消除这种不必要的僵化,这可能会浪费许多开发人员的有用工时。

我在这个问题上工作了2天,对我来说工作是添加自定义用户代理,就像在这个链接中一样

法典

var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");