微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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给我这个结果

enter image description here

当我尝试从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: 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,… }​​target: XMLHttpRequest { __zone_symbol__xhrSync: false,… }​​
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:

铬也显示出来

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”,约束);它应该工作.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐