'webapi not reachable through application but reachable in browser
We have developed WebAPI application and published on server. This WebAPI is referenced in one of our application. Some users have reported that the service end points are not reachable through application, though it can be accessed in browser. It is working fine with most of the users. What may be the issue? How should I investigate? Here is the code we have written to test if service endpoints are reachable:
HttpWebResponse response = null;
string webApiURL = "WebAPIAddress";
Uri url = new Uri(webApiURL);
WebRequest request = WebRequest.Create(url);
request.Timeout = 15000;
response = (HttpWebResponse)request.GetResponse();
The response is null.
Solution 1:[1]
Can you wrap a try/catch around this logic to see if an exception is being thrown? Usually a null response points to an unhandled exception. I have seen issues with hitting web APIs for certain users based on CORS issues.
Review your WebApiConfig and verify your URLs that are trying to hit this API are whitelisted, I left a sample of how I create Cors attribute, the testString is a list of URLs I want to allow to hit this API so it prevents unauthorized access:
EnableCorsAttribute cors;
if (IsPreProd)
{
cors = new EnableCorsAttribute(
testString,
"Content-Type, Access-Control-Allow-Headers," + " Authorization, X-Requested-With, Accept, Allow-DB",
"OPTIONS,GET,POST");
//cors = new EnableCorsAttribute(testString, "*", "POST,OPTIONS") { SupportsCredentials = true };
}
else if (!ServerEnv.IsProd)
{
cors = new EnableCorsAttribute(
"*",
"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin," + " Authorization, X-Requested-With, Accept, Allow-DB",
"OPTIONS,GET,POST");
//cors = new EnableCorsAttribute(testString, "*", "OPTIONS,GET,POST") { SupportsCredentials = true };
}
else
{
cors = new EnableCorsAttribute(
prodString,
"Content-Type, Access-Control-Allow-Headers," + " Authorization, X-Requested-With, Accept, Allow-DB",
"OPTIONS,GET,POST");
//cors = new EnableCorsAttribute(prodString, "*", "POST,OPTIONS") { SupportsCredentials = true };
}
// Web API configuration and services
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kozmocreamer |
