gpt4 book ai didi

c# - WebApi2 跨源请求被 Angular 前端阻止

转载 作者:行者123 更新时间:2023-11-30 12:38:31 27 4
gpt4 key购买 nike

角度网络应用程序:

http://localhost:57729/ 
VS 2017, Core 2.1

应用程序接口(interface):

http://localhost:3554
VS 2017, .Net 4.6

我遇到了 cors 问题,一直在实现不同的解决方案,但到目前为止没有成功。在这种情况下不会发生身份验证。我有测试 API Controller ,它有一个返回 OK 响应的 get 方法。

直接执行测试 http://localhost:3554/MWAPI/Test 给我这个结果

enter image description here

当我尝试从 Angular 网络应用程序运行它时,我遇到了以下 cors 问题

跨源请求被阻止:同源策略不允许读取位于 http://localhost:3554/MWAPI/test 的远程资源。 (原因:CORS header “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

这是我现在拥有的...

网络配置:

 <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,连接没有问题

  1. Telerik fiddler
  2. 创建了一个快速的 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: 88583​​total: 0​​type: "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 而不是 * 作为来源

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 origin的地方在哪里?

我也做了以下测试,结果还是一样。

  • 只保留web.config和注释的注册码
  • 注释web.config并保留注册码

更新 4:工作解决方案@VishalAnand 评论和 chrome 帮助解决了这个问题。

  1. 从 web.config 中删除了以下内容


  2. 移除了 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 方法工作。我还没有测试过放置/发布/删除,希望它们也能正常工作。

最佳答案

请尝试删除 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);它应该有效。

关于c# - WebApi2 跨源请求被 Angular 前端阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777866/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com