在启用OWIN的应用程序中生成令牌期间出现Access-Control-Allow-Origin错误

问题描述 投票:-1回答:1

我正在使用Angular 8应用程序中的C#Web API + CORS + Owin。生成令牌时出现错误。我看过各种文章,但无法解决问题。

从原始位置访问“ http://localhost:60544/Token”处的XMLHttpRequest“ http://localhost:4200”已被CORS政策阻止:否请求中存在“ Access-Control-Allow-Origin”标头资源。

Global.asax.cs

protected void Application_Start()
        {
           // AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);   
        }

        protected void Application_BeginRequest()
        {                
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {                    
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, No-Auth");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Startup.cs

public void Configuration(IAppBuilder app)
        {            
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

WebApiConfig.cs

public static void Register(HttpConfiguration config)
        {            
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Filters.Add(new LoggingFilterAttribute());
            config.Filters.Add(new CustomExceptionFilterAttribute());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings =
            new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            };
        }

web.config

<system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <directoryBrowse enabled="true" />
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="30000000" />
      </requestFiltering>
    </security>    
  </system.webServer>

以下参考文献已添加到我的解决方案中:-

  • Microsoft.AspNet.Identity.Owin
  • Microsoft.Owin Microsoft.Owin.Cors
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Security.OAuth

请帮助我解决这个问题。

cors asp.net-web-api2 access-token access-control owin-middleware
1个回答
0
投票

请尝试通过在您的web.config文件中添加它来进行尝试,将其从Application_Begin请求中删除,我认为这可能对您有用。

 <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
         <add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
      </httpProtocol>
  </system.webServer>

我在我这边也经历了同样的事情,通过这样做可以解决它。

© www.soinside.com 2019 - 2024. All rights reserved.