http://localhost:57729/ VS 2017,Core 2.1
API:
http://localhost:3554VS 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)’不匹配).
我经历过多种资源,但仍然无法为我工作.
Enable CORS in Web API 2
https://www.codeproject.com/Articles/617892/Using-CORS-in-ASP-NET-WebAPI-Without-Being-a-Rocke
https://www.infoworld.com/article/3173363/application-development/how-to-enable-cors-on-your-web-api.html
这就是我现在拥有的……
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",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,'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,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,'cironunes'); * @returns returns T string/number/model */ put<T>(url: string,params: any | null = null): Observable<httpEvent<T>> { url = `${this.baseUrl}${this.baseAPI}/${url}`; return this.http .put<T>(url,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: errorbubbles: falsecancelBubble: falsecancelable: falsecomposed: falsecurrentTarget: nulldefaultPrevented: falseeventPhase: 0explicitOriginalTarget: XMLhttpRequest { __zone_symbol__xhrSync: false,__zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test",readyState: 4,… }isTrusted: truelengthComputable: falseloaded: 0originalTarget: XMLhttpRequest { __zone_symbol__xhrSync: false,… }target: XMLhttpRequest { __zone_symbol__xhrSync: false,… }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: falsestatus: 0statusText: "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",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: "*",methods: "*");config.EnableCors(cors);//var constraints = new { httpMethod = new httpMethodConstraint(httpMethod.Options) };//config.Routes.IgnoreRoute("OPTIONS",constraints);
它适用于get方法.我没有测试过put / post / delete,希望这些也能正常工作.
解决方法 请尝试删除config.Routes.IgnoreRoute(“OPTIONS”,“* pathInfo”,约束);它应该工作. 总结以上是内存溢出为你收集整理的c# – 从角度前端阻止的WebApi2跨源请求全部内容,希望文章能够帮你解决c# – 从角度前端阻止的WebApi2跨源请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)