从角度前端阻止WebApi2跨域请求

时间:2018-08-10 01:55:13

标签: c# cors asp.net-web-api2 angular6

Angular WebApp:

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

API:

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

我正在讨论cors问题,一直在实施不同的解决方案,但到目前为止没有成功。在这种情况下,不会进行身份验证。我有测试API控制器,它有一个get方法,该方法返回OK响应。

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

enter image description here

当我尝试从Angular Web应用程序运行它时,我遇到了以下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

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", "MWAPI/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });       
}

已检查API是否具有以下内容,并且连接没有问题

  1. Telerik Fiddler
  2. 创建了一个快速的WinForms应用程序,并通过HttpClient和async方法调用了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.

它在哪里不喜欢允许来源?

我还通过做以下仍然相同的结果进行了测试。

  • 只保留了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方法。我尚未测试放置/发布/删除,希望它们也能正常工作。

2 个答案:

答案 0 :(得分:1)

请尝试删除config.Routes.IgnoreRoute(“ OPTIONS”,“ * pathInfo”,约束);而且应该可以。

答案 1 :(得分:0)

尝试使用控制器的EnableCors属性

[EnableCors(origins: "http://mywebclient.site.net", headers: "*", methods: "*")]

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api