Currently, I am working on a project that requires me to create a REST API for clients. This API will retrieve data from a database and return it in JSON format. Below is the code for my controller:
[Models.AllowCors]
public HttpResponseMessage Get(string Id)
{
string ClearName = Id.Replace("_", " ");
IQueryable<Models.User> userQuery =
from user in Models.TableAccesser.Users_Table where
user.Name == ClearName
select user;
return Request.CreateResponse(HttpStatusCode.OK, userQuery);
}
The issue I am facing is that I can only access the API from the same PC where the Web API is running. The link I use to reach it looks like this:
my_ip:54780/users/parameters
When I call from the same PC, everything works fine. However, I cannot access it from another PC. I have tried enabling CORS in different ways, but none of them seem to work. First, I attempted:
Enabling CORS in webapiconfig.cs:
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
This did not solve the issue.
Next, I added a new entry in web.config:
<add name="Access-Control-Allow-Origin" value="*"/>
Unfortunately, this approach also did not work.
Lastly, I tried adding a function:
public class AllowCors : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext == null) { throw new ArgumentException("ActionExecutedContext"); } else { actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin"); actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } base.OnActionExecuted(actionExecutedContext); } }
I tested using Postman from another PC, as well as XMLHttpRequest and AJAX, but none of these methods worked. There seems to be a 20-second delay, followed by an error response without any additional information.
If you have any suggestions on how I can resolve this access issue with the API, I would greatly appreciate it. The API will eventually be utilized by a mobile application, so it needs to support simple requests.
Thank you in advance for your assistance.