Javascript 从另一台pc访问.net web api
我正在做一个项目,我需要为客户端提供一个RESTAPI,它将以JSON格式从数据库返回一些数据。 '到目前为止,这是我的控制器代码:Javascript 从另一台pc访问.net web api,javascript,c#,ajax,asp.net-apicontroller,Javascript,C#,Ajax,Asp.net Apicontroller,我正在做一个项目,我需要为客户端提供一个RESTAPI,它将以JSON格式从数据库返回一些数据。 '到目前为止,这是我的控制器代码: [Models.AllowCors] public HttpResponseMessage Get(string Id) { string ClearName = Id.Replace("_", " "); IQueryable<Models.User> userQuery =
[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);
}
如果我在同一台电脑上打电话,效果很好,但我在另一台电脑上打不到。我尝试了几种方式允许cors,但都不起作用。我试过:
- 在webapiconfig.cs中启用cors:
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
- 然后我尝试在web.config中添加一个新条目:
<add name="Access-Control-Allow-Origin" value="*"/>
感谢您的回复。从您的问题来看,您似乎需要打开Web API计算机上的端口。在您的情况下,您需要打开端口
54780
打开您的端口非常容易,此处是Microsoft页面,其中包含有关如何操作的说明:
请注意,如果您使用的是第三方防火墙,例如带有防病毒软件的防火墙,则需要打开该应用程序中的端口。您是在工作/服务器环境中还是在家庭环境中进行测试?您是否可以从其他机器访问您的电脑?有防火墙阻止请求吗?谢谢,这就是问题所在。现在一切都好了。
<add name="Access-Control-Allow-Origin" value="*"/>
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);
}
}