【问题标题】:Angular 4 / Asp.net Web API - No 'Access-Control-Allow-Origin' header is presentAngular 4 / Asp.net Web API - 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2018-02-15 16:06:59
【问题描述】:

我正在尝试从角度调用 API 并收到此错误。 我不想在 Angular 中设置代理,而是在 Angular 4 和 Web API 中允许 CORS。

以下是我的代码:

let reHeader: RequestOptions = new RequestOptions();
        reHeader.headers = new Headers();
        reHeader.headers.append("content-type", "application/json");
        reHeader.headers.append("x-api-key", store.APIKey);
        reHeader.headers.append('Access-Control-Allow-Origin','*');
        reHeader.headers.append('Access-Control-Allow-Methods', "GET, POST, PATCH, PUT, DELETE, OPTIONS")
        reHeader.headers.append('Access-Control-Allow-Headers', "Origin, Content-Type, X-Auth-Token")
        switch (rtype) {
            case "get":
                let query: string = "";
                action.ActionParams.forEach(m => {
                    query += "&" + m.Key + "=" + m.Value;
                });
                url = url + query;
                return this.http.get(url, reHeader);
            default:
                return Observable.of(null);
        }

以及来自startup.cs中的WEB API

    public void Configuration(IAppBuilder app)
            {
                app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// ASPNETCORE_ENVIRONMENT should be set to 'Development'
            if (env != null && env.IsDevelopment())
            {
                app.UseErrorPage(ErrorPageOptions.ShowAll);
            }

            var config = new HttpConfiguration();
            ConfigureWebApi(config);
            // Swagger
            SwaggerConfig.Register(config);
            // Register routes
            WebApiConfig.Register(config);
             }

我检查了其他帖子,但仍然没有得到解决方案。 - Angular 2 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header

【问题讨论】:

标签: c# angular asp.net-web-api


【解决方案1】:

在 Global.asax 中添加以下代码并尝试

protected void Application_BeginRequest(Object sender, EventArgs e)
        {

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2014-12-15
    • 2017-12-16
    • 2019-01-12
    • 1970-01-01
    • 2020-11-06
    • 2020-05-18
    相关资源
    最近更新 更多