c# – 从角度前端阻止的WebApi2跨源请求
作者:互联网
Angular WebApp:
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 Web应用程序运行它时,我遇到了以下的cors问题
跨源请求已阻止:同源策略禁止在http:// localhost:3554 / MWAPI / test读取远程资源. (原因:CORS标题’Access-Control-Allow-Origin’与'(null)’不匹配).
我经历过多种资源,但仍然无法为我工作.
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方法.这里没问题.
我错过了这里的其他东西,现在无法查明.你看到我在这里可能遗失的任何东西吗?
更新1:
这是来自前端的电话
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));
}
}
更新2:
完整的错误响应
{…}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:
铬也显示出来
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而不是*来源
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.
哪个不喜欢允许来源?
我也通过做了以下测试,结果仍然相同.
>仅保留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,希望这些也能正常工作.
解决方法:
请尝试删除config.Routes.IgnoreRoute(“OPTIONS”,“* pathInfo”,约束);它应该工作.
标签:c,cors,asp-net-web-api2,angular6 来源: https://codeday.me/bug/20190705/1388103.html