Ronald
Ronald

Reputation: 1113

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;

Upvotes: 1

Views: 1797

Answers (3)

yehoni amran
yehoni amran

Reputation: 29

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)");

Upvotes: 1

Hafiz Adewuyi
Hafiz Adewuyi

Reputation: 378

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.

Upvotes: 1

Ronald
Ronald

Reputation: 1113

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;

Upvotes: 2

Related Questions