我正在设计一个WebApi,MVC.NET将由AngularJS前端使用。但是,当用户尝试注册时,我在CORS方面有一些问题。
因此,在我的Web.Config中,我有以下内容:-
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE, TOKEN" />
</customHeaders>
</httpProtocol>它对登录屏幕很好(用户正确登录到系统)。然而,当我尝试注册一个新用户时,我会得到以下错误:
XMLHttpRequest无法加载http://localhost:45668//api/Account//Register。对飞行前的响应具有无效的HTTP状态代码404
因此,在WebConfigApi.cs中,我包含以下代码:-
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
var cors = new EnableCorsAttribute("http://localhost", "*", "*");
config.EnableCors(cors);
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}在注册用户时引发以下错误:
XMLHttpRequest无法加载http://localhost:45668//api/Account//Register。对飞行前请求的响应不会通过访问控制检查:“访问-控制-允许-原产地”报头包含多个值'http://localhost,*',但只允许一个。因此,“http://localhost”源是不允许访问的。
如果删除web.config CustomHeaders,则注册工作正常,但是登录会引发CORS错误。
我如何才能做到这一点,并拥有一个集中的CORS认证?
谢谢你的帮助和时间!
发布于 2016-04-21 13:23:15
在web配置中不需要设置自定义标题。您可以通过以下代码启用CORS。
[EnableCors(origins: "http://localhost:45668//api/Account//Register", headers: "*", methods: "*")]https://stackoverflow.com/questions/36768517
复制相似问题