C# ASP.NET Web Api在跨源获取令牌时遇到问题
我从前端(Node.js和Ajax)使用跨源代码登录Web Api时遇到一些问题。我得到以下错误:C# ASP.NET Web Api在跨源获取令牌时遇到问题,c#,asp.net,ajax,asp.net-identity,asp.net-web-api,C#,Asp.net,Ajax,Asp.net Identity,Asp.net Web Api,我从前端(Node.js和Ajax)使用跨源代码登录Web Api时遇到一些问题。我得到以下错误: XMLHttpRequest cannot load http://localhost:61102/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. T
XMLHttpRequest cannot load http://localhost:61102/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500.
此问题仅在我尝试调用/Token登录时发生。我可以访问其他路线并完美注册。这是我的密码:
Startup.cs:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureAuth(app);
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
}
Startup.Auth.cs:
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
你使用CORS的方式和我过去有点不同。我已经做了很多次,并取得了相对的成功 在WebApi项目中添加对
System.Web.Cors
的引用,并将以下内容添加到WebApiConfig.cs
文件中的Register
方法中:
public static void Register(HttpConfiguration config)
{
config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
更多深入教程可在此处找到:
天哪,我让它工作了。不确定它是好的还是正确的方法(可能不是,但它是有效的)。我所做的是删除了app.UseCors(CorsOptions.AllowAll)和我的代码中的所有其他启用cors的东西非常愤怒,并将其添加到我的web.config中
:
在GrantResourceOwnerCredentials()中的applicationAuthProvider.cs中,我在函数顶部添加了以下行:
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
这是一些完全相同的代码,我曾经尝试过很多次,但这次我不知道是什么使它工作。我登录了我的电脑,当我回来尝试它时,它突然工作了。这里有一些巫毒的东西,但这可能是正确的方法。您是否尝试过使用var cors=new EnableCorsAttribute(“,”,“*”);配置使能cors(cors);在配置方法中?@Yousuf是的,它不起作用。它应该在那里吗?嘿!这是我第一次尝试的,它适用于所有方面,除了给我错误的/token端点。不过,这一切在Postman中都非常有效,我可以从/token获得访问密钥。它和我上面的代码一样该死,真的吗?我会继续挖的。太好了,谢谢。还有,可能是我的ajax请求导致的吗?我从react应用程序中的服务发送它。我已经用javascript更新了这个问题。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:8080"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</customHeaders>
</httpProtocol>
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });