我有一个aurelia客户端和一个网络服务器。当我使用localhost并且我在同一台机器上运行时它工作正常。
但是当我想从另一台机器访问服务器页面加载但是api调用会出现以下错误:
请求的资源上没有Access-Control-Allow-Origin
标头。
我正在使用owin而且我的未知我需要为owin启用CORS。
我在创业课中做了以下几点: -
UPDATE 我已经用Nenad的输入更新了我的课程,但仍然得到同样的错误。 下面我添加了来自客户端的电话。
public void Configuration(IAppBuilder app)
{
this.container = new Container();
// Create the container as usual.
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IWebDeps, WebDeps>(Lifestyle.Singleton);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration, Assembly.GetExecutingAssembly());
container.Verify();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// Configure Web API for self-host.
var config = new HttpConfiguration()
{
DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container)
};
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//// Custom Middleare
app.Use(typeof(CustomMiddleware));
app.UseWebApi(config);
//New code:
app.Run(context =>
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Hello, world.");
});
}
我的主程序正在调用startUp类: -
using (Microsoft.Owin.Hosting.WebApp.Start<Startup>("http://localhost:8080"))
{
Console.WriteLine("Press [enter] to quit...");
Console.ReadLine();
}
客户端代码,192.168.178.23是服务器的IP。
let baseUrl2 = "http://192.168.178.23:8080/api/status/getStatus";
getStatus() {
return this.client.get(baseUrl2)
.then(response => {
return this.parseJSONToObject(response.content);
});
}
Chrome中的错误:
XMLHttpRequest无法加载 http://192.168.178.23:8080/api/status/getStatus。没有 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://localhost:9000” 访问。响应的HTTP状态代码为400。
现在应该启用Cors吗?但是在进行api调用时我仍然会收到错误消息。我错过了任何步骤吗?我们这个认可错了吗?
欢迎任何建议!
答案 0 :(得分:1)
您必须配置WebAPI以使用CORS。
安装Nuget包:
Install-Package Microsoft.AspNet.WebApi.Cors
在HttpConfiguration
对象上启用CORS:
config.EnableCors();
在控制器上添加[EnableCors]
属性:
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "www.example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
或通过HttpConfig
全球注册:
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
答案 1 :(得分:0)
添加此行并检查
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
并删除,
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
这对我有用。
答案 2 :(得分:0)
事实证明,当启动OWIN时,地址应为http:// *:8080。而不是本地主机。