来自 Angular 前端的 WebApi2 跨源请求被阻止
WebApi2 Cross-Origin Request Blocked from Angular Front End
Angular 网络应用程序:
http://localhost:57729/
VS 2017, Core 2.1
API:
http://localhost:3554
VS 2017, .Net 4.6
我遇到了 cors 问题,一直在实施不同的解决方案,但到目前为止没有成功。在这种情况下不会发生身份验证。我有测试 API 控制器,它有一个返回 OK 响应的 get 方法。
直接执行测试http://localhost:3554/MWAPI/Test
给我这个结果
当我尝试从 Angular 网络应用程序 运行 它时,我遇到了以下 cors 问题
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3554/MWAPI/test. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
我已经查看了多种资源,但它仍然不适合我。
Enable CORS in Web API 2
https://www.codeproject.com/Articles/617892/Using-CORS-in-ASP-NET-WebAPI-Without-Being-a-Rocke
这是我现在拥有的...
Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
//url is without the trailing slash
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:57729", "*", "*");
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*");
config.EnableCors(cors);
var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
//testing... or remove all formats
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
//testing... and add indenting and camel case if we need
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApiWithId", "MWAPI/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "MWAPI/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "MWAPI/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "MWAPI/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
已检查 API 以下内容并且连接没有问题
- Telerik Fiddler
- 创建了一个快速的 WinForms 应用程序并通过 HttpClient 和异步方法调用了 get/post/delete/put 方法。没问题。
我在这里遗漏了一些东西,现在无法确定。你看到我在这里可能遗漏了什么吗?
更新一:
这是来自前端的调用
app.component 测试函数
handleSomeTests() {
let api = "test"
//standard get,returns HttpStatusCode.OK, "Standard Get executed"
console.log("===Standard Get===");
this.dataService.get<any>(api +'').subscribe(
(res) => {
console.log(res);
},
error => {
//error.message, error.name, error.ok, error.status, error.statusText, error.url
console.log(error);
}
);
}
和数据服务(尚未完成但已完成其基本工作)
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseApi: string = 'MWAPI';
baseUrl: string = 'http://localhost:3554/';
retries: number = 0;
constructor(private http: HttpClient) { }
/**
* A GET method
* @param url api url without leading / and MWAPI/ as well
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
get<T>(url: string, params: any | null = null): Observable<T> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.get<T>(url, { params })
.pipe(retry(this.retries));
}
/**
* A POST method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
post<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.post<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A PUT method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
put<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.put<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A DELETE method
* @param url api url without leading / and MWAPI/ as well
*/
delete(url: string): Observable<object> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.delete(url)
.pipe(retry(this.retries));
}
}
更新二:
完整的错误响应
{…}error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
timeStamp: 88583total: 0type: "error"<prototype>: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
<prototype>: Object { constructor: HttpErrorResponse() } app.component.ts:81:8
更新3:
chrome 也显示
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
我改为关注,使用 url 而不是 * 作为 origins
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*")
现在 chrome 显示此错误
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:57729, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
不喜欢allow的出处在哪里?
我也做了如下测试,结果还是一样。
- 只保留web.config和注释的注册码
- 评论web.config并保留注册码
更新 4:工作解决方案
@VishalAnand 评论和 chrome 帮助解决了这个问题。
从 web.config
中删除了以下内容
移除了 webapiconfig 注册方法的约束,只留下前两行。
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
config.EnableCors(cors);
//var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
//config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
正在为 get 方法工作。我还没有测试过 put/post/delete,希望这些也能正常工作。
尝试控制器的 EnableCors
属性
[EnableCors(origins: "http://mywebclient.site.net", headers: "*", methods: "*")]
请尝试移除 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);它应该可以工作。
Angular 网络应用程序:
http://localhost:57729/
VS 2017, Core 2.1
API:
http://localhost:3554
VS 2017, .Net 4.6
我遇到了 cors 问题,一直在实施不同的解决方案,但到目前为止没有成功。在这种情况下不会发生身份验证。我有测试 API 控制器,它有一个返回 OK 响应的 get 方法。
直接执行测试http://localhost:3554/MWAPI/Test
给我这个结果
当我尝试从 Angular 网络应用程序 运行 它时,我遇到了以下 cors 问题
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3554/MWAPI/test. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
我已经查看了多种资源,但它仍然不适合我。
Enable CORS in Web API 2
https://www.codeproject.com/Articles/617892/Using-CORS-in-ASP-NET-WebAPI-Without-Being-a-Rocke
这是我现在拥有的...
Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
//url is without the trailing slash
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:57729", "*", "*");
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*");
config.EnableCors(cors);
var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
//testing... or remove all formats
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
//testing... and add indenting and camel case if we need
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApiWithId", "MWAPI/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "MWAPI/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "MWAPI/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "MWAPI/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
已检查 API 以下内容并且连接没有问题
- Telerik Fiddler
- 创建了一个快速的 WinForms 应用程序并通过 HttpClient 和异步方法调用了 get/post/delete/put 方法。没问题。
我在这里遗漏了一些东西,现在无法确定。你看到我在这里可能遗漏了什么吗?
更新一:
这是来自前端的调用
app.component 测试函数
handleSomeTests() {
let api = "test"
//standard get,returns HttpStatusCode.OK, "Standard Get executed"
console.log("===Standard Get===");
this.dataService.get<any>(api +'').subscribe(
(res) => {
console.log(res);
},
error => {
//error.message, error.name, error.ok, error.status, error.statusText, error.url
console.log(error);
}
);
}
和数据服务(尚未完成但已完成其基本工作)
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseApi: string = 'MWAPI';
baseUrl: string = 'http://localhost:3554/';
retries: number = 0;
constructor(private http: HttpClient) { }
/**
* A GET method
* @param url api url without leading / and MWAPI/ as well
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
get<T>(url: string, params: any | null = null): Observable<T> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.get<T>(url, { params })
.pipe(retry(this.retries));
}
/**
* A POST method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
post<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.post<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A PUT method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
put<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.put<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A DELETE method
* @param url api url without leading / and MWAPI/ as well
*/
delete(url: string): Observable<object> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.delete(url)
.pipe(retry(this.retries));
}
}
更新二:
完整的错误响应
{…}error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
timeStamp: 88583total: 0type: "error"<prototype>: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
<prototype>: Object { constructor: HttpErrorResponse() } app.component.ts:81:8
更新3:
chrome 也显示
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
我改为关注,使用 url 而不是 * 作为 origins
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*")
现在 chrome 显示此错误
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:57729, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
不喜欢allow的出处在哪里?
我也做了如下测试,结果还是一样。
- 只保留web.config和注释的注册码
- 评论web.config并保留注册码
更新 4:工作解决方案 @VishalAnand 评论和 chrome 帮助解决了这个问题。
从 web.config
中删除了以下内容
移除了 webapiconfig 注册方法的约束,只留下前两行。
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "*", headers: "*", methods: "*"); config.EnableCors(cors); //var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) }; //config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
正在为 get 方法工作。我还没有测试过 put/post/delete,希望这些也能正常工作。
尝试控制器的 EnableCors
属性
[EnableCors(origins: "http://mywebclient.site.net", headers: "*", methods: "*")]
请尝试移除 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);它应该可以工作。