简体   繁体   中英

404 when calling a c# web api from another c# web forms application

I have created a simple web api and when I access this from IE the web api returns exactly what I expected. However, now I tried to access the same web api from a web forms application using httpclient. But now I get a 404 error. But the api seems to work, because I do receive results when using a browser. Any ideas what goes wrong? This is the code:

 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;

This is the code that worked.

 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;

I work on this problem 2 days,and what work for me is to add custom user agent, like in this link

code

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

Wow. I was experiencing this same error this weekend and I cannot imagine how flimsy the cause of the problem was.

This is what worked for me:

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

client.BaseAddress = new Uri(_baseAddress);
string result = client.GetStringAsync("controllerURL").Result.ToString();

The combinations of _baseAddress and controllerURL that caused the 404 error for me are as follows:

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

or

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

or

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

I sincerely hope something is done soon to remove this needless rigidity that is likely to waste many a developer's useful man hours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM