C# 执行GET请求时Angular 5 Web API 2 CORS错误

C# 执行GET请求时Angular 5 Web API 2 CORS错误,c#,angular,cors,asp.net-web-api2,C#,Angular,Cors,Asp.net Web Api2,我使用Angular5应用程序和Web API2作为服务层。我使用基于令牌的身份验证框架OAuth Owin。CORS代码适用于令牌生成请求,但对于后续GET请求,它不起作用,并且我收到401 not AUTHED错误 从Angular生成令牌的标头如下所示: this._httpHeader = { headers: { 'Content-Type': 'application/x-www-form-urlencoded'

我使用Angular5应用程序和Web API2作为服务层。我使用基于令牌的身份验证框架OAuth Owin。CORS代码适用于令牌生成请求,但对于后续GET请求,它不起作用,并且我收到401 not AUTHED错误

从Angular生成令牌的标头如下所示:

 this._httpHeader = {
        headers: {         
          'Content-Type': 'application/x-www-form-urlencoded'
        }
getCurrentUserLogin(): Observable<any> {    
    if (sessionStorage.getItem('AccessToken') == null || sessionStorage.getItem('AccessToken') == 'undefined') {


      let requestOptions = new RequestOptions({ headers: this._httpHeader, withCredentials:  true  }); 
      return this._http.get(this._baseURL + "Authentication", requestOptions)

        .map(res => {
          if (res != null) {
            return res.json();
          }
        })        
        .do(data => console.log('Token: ' + JSON.stringify(data)))
        .catch(this.handleError);

    }
令牌生成服务如下所示:

 this._httpHeader = {
        headers: {         
          'Content-Type': 'application/x-www-form-urlencoded'
        }
getCurrentUserLogin(): Observable<any> {    
    if (sessionStorage.getItem('AccessToken') == null || sessionStorage.getItem('AccessToken') == 'undefined') {


      let requestOptions = new RequestOptions({ headers: this._httpHeader, withCredentials:  true  }); 
      return this._http.get(this._baseURL + "Authentication", requestOptions)

        .map(res => {
          if (res != null) {
            return res.json();
          }
        })        
        .do(data => console.log('Token: ' + JSON.stringify(data)))
        .catch(this.handleError);

    }
WebAPIConfig.cs

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            EnableCorsAttribute cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["AllowAccessToDomain"], "*", "*") { SupportsCredentials = true };
            config.EnableCors(cors);

            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());


            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
我能够使用上述CORS代码成功生成令牌。但对于以下来自Angular的服务调用,它给出了“未授权”错误:

来自Angular的正常GET请求的标头:

this._httpHeader = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer ' + sessionStorage.getItem('AccessToken')
        }
getHomeAccountTemplates(): Observable<HomeAccountTemplate[]> {

      let requestOptions = new RequestOptions({ headers: this._httpHeader, withCredentials: true });
    return this._http.get(this._baseURL + "Account/AccountTemplates", requestOptions)

        .map(res => {          
          if (res != null) {
            return res.json();
          }
        })        
        .catch(this.handleError);
  }
来自Angular的正常服务呼叫:

this._httpHeader = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer ' + sessionStorage.getItem('AccessToken')
        }
getHomeAccountTemplates(): Observable<HomeAccountTemplate[]> {

      let requestOptions = new RequestOptions({ headers: this._httpHeader, withCredentials: true });
    return this._http.get(this._baseURL + "Account/AccountTemplates", requestOptions)

        .map(res => {          
          if (res != null) {
            return res.json();
          }
        })        
        .catch(this.handleError);
  }
getHomeAccountTemplates():可观察{
let requestOptions=new requestOptions({headers:this.\u httpHeader,withCredentials:true});
返回此。_http.get(此。_baseURL+“帐户/帐户模板”,请求选项)
.map(res=>{
如果(res!=null){
返回res.json();
}
})        
.接住(这个.把手错误);
}
用于上述服务调用的Web API控制器:

[Authorize]
    public class AccountController : ApiController
    {
private readonly IAccountService _AccntServices;

        #region Constructors

        public AccountController()
        {
            _AccntServices = new AccountService();
        }

        #endregion

        [HttpGet]
        [Route("api/Account/AccountTemplates")]
        public List<HomeAccountTemplate> GetAccountTemplates()
        {
            //int InstanceID = Convert.ToInt32(((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(c => c.Type.Contains("InstanceId")).Value);
            int InstanceID = 1;
            return _AccntServices.GetAccountTemplates(InstanceID);
        }
}
[授权]
公共类AccountController:ApicController
{
专用只读IAccountService\u AccntServices;
#区域构造函数
公共账户控制员()
{
_AccntServices=新的AccountService();
}
#端区
[HttpGet]
[路线(“api/账户/账户模板”)]
公共列表GetAccountTemplates()
{
//int InstanceID=Convert.ToInt32(((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(c=>c.Type.Contains(“InstanceID”)).Value);
int InstanceID=1;
return\u AccntServices.GetAccountTemplates(InstanceID);
}
}

上面的控制器没有被命中,执行在Global.asax停止。我收到“未授权”错误。请帮助解决此问题。

CORS不应影响GET请求。看起来您的web服务器(IIS?)使用此
授权
标头拒绝请求。例如,如果在IIS中禁用匿名访问并启用windows身份验证,则无法使用承载令牌。我尚未部署它,但在Web配置中启用了windows身份验证,因为我使用windows登录的用户名根据应用程序数据库中的用户表对用户进行身份验证。当我遇到此问题时,我在谷歌上找到了一个类似“IIS为单路由启用windows身份验证”和为应用程序的单路由启用windows身份验证('/login')的解决方案。你能提供你所关注的链接吗?正如我所说,我还没有部署应用程序,所以如何在Web配置中为单个路由启用windows身份验证?未授权不是CORS问题。您是否在Chrome开发工具中检查了您的请求头,以确保在发送请求时发送了正确的头?