Angular 2

时间:2016-09-30 10:15:50

标签: wcf angular

我正在使用Angular 2从WCF服务获取数据。 我正在调用返回令牌的Login方法。

对于获取项目数据,我正在使用GET方法,在该请求中,我们需要在标头中传递令牌。

但是它给出了错误:

  

XMLHttpRequest无法加载http://192.168.0.149/API/Service1.svc/Datalist。预检的响应无效(重定向)。预检响应中的Access-Control-Allow-Headers不允许使用请求标头字段标记。

这是我的标题: -

General:
Request URL:http://pct149/ITM_API/Service1.svc/BHL/Projects

Request Method:OPTIONS

Status Code:200 OK

Remote Address:192.168.0.149:80

这是我的Angular服务,我在其中调用WCF服务: -

   import {Injectable} from "@angular/core"

   import { Http, Response, RequestOptions, Headers } from "@angular/http"

   import { Observable } from 'rxjs/Rx';

   import {HttpClient } from "@service/http-client";

   @Injectable()

   export class AppService {
         Hero = [];

        baseUrl = "http://pct149/ITM_API/Service1.svc/BHL/";

        constructor(private _http: Http, private httpClient: HttpClient) {
        }

        Authentication() {
             return this._http.get(this.baseUrl +        "Login/harshad.bhola@server1.com/1")
        .map((response: Response) => {
            let dataToken = response.json();
            let Token = dataToken.Token;
            if (Token != null & dataToken != null) {
                return Token;
            }
            else {
                return '';
            }
        })
        .catch(this.handleError);
    }

       loadProjects(Token) {

         return this._http.get(this.baseUrl + "Projects", { headers: {  'token': Token.trim() } })
        .map((responseData: Response) => {
              let appData = responseData.json();
              console.log(appData);
              return appData;
          });
    }

       private handleError(error: Response) {
         console.error(error);
         return Observable.throw(error.json().error || 'Server error');
    }

}

以下是我调用服务方法的组件: -

     import {Component} from "@angular/core";

     import { RouterOutlet, RouterLink, RouterModule, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from "@angular/router";

     import { HTTP_PROVIDERS, HTTP_BINDINGS } from '@angular/http';

     import {AppService } from "@service/app.service";

     @Component({
        selector: 'app',
        templateUrl: 'htmls/app.html',
        directives: [ROUTER_DIRECTIVES],
        providers: [AppService]
     })

    export class ProjectListComponent {
           Projects = [];
           result = '';

    constructor(private _appService: AppService) {
       this.GetProject();
    }

     GetProject() {
       this._appService.Authentication().subscribe(result =>  {this._appService.loadProjects(result).subscribe(newProject => this.Projects = newProject); });
  }
}

在我的WCF服务的Global.asax下面的代码:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.Flush();
        }
    }

如果我错了,请帮助我。

1 个答案:

答案 0 :(得分:1)

您需要在CORS支持的支持方法列表中添加选项。我使用webapi 2所以我这样做:

来自webApiConfig.cs的

 var cors = new EnableCorsAttribute("*", "*", "GET,PUT,POST,PATCH,DELETE,OPTIONS");

我还必须捕获预检请求并添加所需的标头: 来自global.asax.cs:

protected void Application_BeginRequest()
{
   var req = HttpContext.Current.Request;
   var res = HttpContext.Current.Response;

   var val = res.Headers.GetValues("Access-Control-Allow-Origin");
   if (val == null)
   {
      if (!req.Url.ToString().ToLower().Contains("token") || (req.Url.ToString().ToLower().Contains("token") && req.HttpMethod == "OPTIONS"))
      {
         res.AppendHeader("Access-Control-Allow-Origin", "http://localhost:4200");
      }
   }



   if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
   {
      res.AppendHeader("Access-Control-Allow-Credentials", "true");
      res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
      res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");



      res.StatusCode = 200;
      res.End();
    }
 }

希望这有帮助。