我使用angular 4 webapi2

时间:2018-12-18 10:48:23

标签: angular cors webapi2

我正在使用Angle 4和Web API开发应用程序。即使我将代码保存在Web.config,启动,WebApiConfig和Controller中,我也收到CORS错误,但仍然出现此错误。我不知道如何解决。这是我的代码示例

Startup.cs

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

WebApiConfig

 var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

Web.Config

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

控制器

 [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ApiVersion1RoutePrefix("Settings")]
    public class SettingsController : ApiController

即使有人要求也从Web配置中删除此标签,我也这样做了

<!--<remove name="OPTIONSVerbHandler" />-->

我的角通话在这里

  public getbyString<T>(apiUrl:any,param: string): Observable<T> {
    let _options = { headers: new HttpHeaders(
      { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer '+ localStorage.getItem('access_token')
      }
    )};
    return this.http.get<T>(this.actionUrl+apiUrl +"?version="+param,_options);
  }

请参阅以下内容查看错误。

enter image description here

我已经完成了所有这一切,但还没有成功。

1 个答案:

答案 0 :(得分:-1)

CORS(跨域资源共享)是服务器说“即使您来自其他来源,我也会接受您的请求”的一种方式。这需要服务器的配合-因此,如果您无法修改服务器(例如,如果您使用的是外部API),则此方法将无效。

修改服务器以添加标头Access-Control-Allow-Origin:*,以从任何地方启用跨域请求(或指定域而不是*)。