Angularjs ASP.NET WebApi对ValidateClientAuthentication上的选项(即使是在context.Validated()上)的400个错误请求进行应答

Angularjs ASP.NET WebApi对ValidateClientAuthentication上的选项(即使是在context.Validated()上)的400个错误请求进行应答,angularjs,asp.net-web-api,typescript,cors,preflight,Angularjs,Asp.net Web Api,Typescript,Cors,Preflight,我有一个WebApi项目的angularjs HTML客户端。当我通过POSTMAN或其他REST客户端测试API时,似乎一切正常 当我开始在angularjs客户端上使用浏览器时,浏览器总是使用选项启动飞行前请求。在那里,我的WebAPI总是回答400个错误请求——我仍然处于“/api/令牌”阶段 我已经将WebAPI项目的每个点都连接到调试器。根据这里关于如何启用CORS的几个答案,我也改变了几点。其中一些我已经尝试过了:更改web.config以添加头,在每个请求上启用cors,将cors

我有一个WebApi项目的angularjs HTML客户端。当我通过POSTMAN或其他REST客户端测试API时,似乎一切正常

当我开始在angularjs客户端上使用浏览器时,浏览器总是使用选项启动飞行前请求。在那里,我的WebAPI总是回答400个错误请求——我仍然处于“/api/令牌”阶段

我已经将WebAPI项目的每个点都连接到调试器。根据这里关于如何启用CORS的几个答案,我也改变了几点。其中一些我已经尝试过了:更改web.config以添加头,在每个请求上启用cors,将cors添加到WebApi启动,在“/token”重写函数处启用cors

以下是我为什么这么做的原因:

Angularjs对“/api/token”的TypeScript调用:

如果我只是将OWIN留在Cors中,添加标题并调用'context.Validated()',一切都会继续。以下是我得到的:

Firefox Network Tab:
--------------------
Request URL: http://local.web.api/api/token
Request method: OPTIONS
Remote address: 127.0.0.1:80
Status code: 400 Bad Request
Version: HTTP/1.1

Request headers:
----------------
Host: local.web.api
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.7,pt-BR;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization
Origin: http://local.web.client
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response headers:
-----------------
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Length: 34
Content-Type: application/json;charset=UTF-8
Date: Tue, 22 Dec 2015 15:24:23 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
我真的很想知道该去哪里。
这对我来说是全新的,而且我确实操作了一些其他WebApi项目+angularjs。

好的,这很糟糕,但我发现了问题。
// http auth interceptor
angularApplication.factory('httpAuthInterceptor', ['$rootScope', '$injector', '$location', ($rootScope, $injector, $location): ng.IHttpInterceptor => {

    var $q: ng.IQService = $injector.get('$q');
    var localStorageService: ng.local.storage.ILocalStorageService = $injector.get('localStorageService');

    return {
        request: (config: ng.IRequestConfig): ng.IRequestConfig => {
            // check if headers are present
            config.headers = config.headers || {};

            // the error was here! I was trying to add properties to config that I think angular was not expecting
            // removing this line solved the issue
            // if (!config.bypassToken) {

            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if (loggedUserInfo) {
                config.headers['Authorization'] = 'Bearer ' + loggedUserInfo.access_token;
            }
            return config;
        },
        responseError: (rejection)  => {
            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if ((rejection.status === 401) && (loggedUserInfo)) {

                // if so, then the user must login againd
                localStorageService.remove('Auth');
                $location.path('/home');
                console.error(rejection);
            }
            return $q.reject(rejection);
        }
    };
}]);
我在angularjs上使用http拦截器,它会自动检查登录用户,并在需要时添加带有
承载
令牌的
授权
头。问题是我做得不对

我在
config
对象中创建了一个新属性,
bypassToken
作为布尔值,它将是添加或不添加
授权
头的标志。删除它实际上修复了代码。不知道为什么,但是现在分析请求,我可以看到所有的头都按照预期发送:使用
内容类型
,在第一个案例中没有正确填充。奇怪的是,angularjs没有发出任何警告

// http auth interceptor
angularApplication.factory('httpAuthInterceptor', ['$rootScope', '$injector', '$location', ($rootScope, $injector, $location): ng.IHttpInterceptor => {

    var $q: ng.IQService = $injector.get('$q');
    var localStorageService: ng.local.storage.ILocalStorageService = $injector.get('localStorageService');

    return {
        request: (config: ng.IRequestConfig): ng.IRequestConfig => {
            // check if headers are present
            config.headers = config.headers || {};

            // the error was here! I was trying to add properties to config that I think angular was not expecting
            // removing this line solved the issue
            // if (!config.bypassToken) {

            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if (loggedUserInfo) {
                config.headers['Authorization'] = 'Bearer ' + loggedUserInfo.access_token;
            }
            return config;
        },
        responseError: (rejection)  => {
            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if ((rejection.status === 401) && (loggedUserInfo)) {

                // if so, then the user must login againd
                localStorageService.remove('Auth');
                $location.path('/home');
                console.error(rejection);
            }
            return $q.reject(rejection);
        }
    };
}]);
//http身份验证拦截器
angularApplication.factory('httpAuthInterceptor',['$rootScope','$injector','$location',($rootScope,$injector,$location):ng.IHttpInterceptor=>{
var$q:ng.IQService=$injector.get(“$q”);
var localStorageService:ng.local.storage.ILocalStorageService=$injector.get('localStorageService');
返回{
请求:(config:ng.IRequestConfig):ng.IRequestConfig=>{
//检查是否存在标题
config.headers=config.headers | |{};
//错误就在这里!我正在尝试向配置中添加我认为angular没有预料到的属性
//删除这一行解决了问题
//如果(!config.bypassToken){
//检查用户是否已登录
var loggedUserInfo=localStorageService.get('Auth');
if(loggedUserInfo){
config.headers['Authorization']='Bearer'+loggedUserInfo.access_令牌;
}
返回配置;
},
响应者:(拒绝)=>{
//检查用户是否已登录
var loggedUserInfo=localStorageService.get('Auth');
如果((拒绝.status==401)和(&(loggedUserInfo)){
//如果是这样,那么用户必须重新登录
localStorageService.remove('Auth');
$location.path('/home');
控制台错误(拒绝);
}
返回$q.reject(拒绝);
}
};
}]);
我感谢你的帮助。 我只是在这里发布这个,以防有人面临类似的问题。
不要弄乱
config
对象!

访问控制请求方法:POST
,选项不允许并返回错误,您需要在配置中包含
选项
,并且
选项
调用必须返回
200确定
内容是不必要的o启用CORS,但我仍然收到400个错误请求。我应该在哪里添加
选项
?什么配置?因为我的WebApi项目达到的唯一点是
ValidateClientAuthentication
,我是否应该返回除调用
context.Validated()
)之外的其他内容?感谢您的链接!也许此链接将非常有用:
// http auth interceptor
angularApplication.factory('httpAuthInterceptor', ['$rootScope', '$injector', '$location', ($rootScope, $injector, $location): ng.IHttpInterceptor => {

    var $q: ng.IQService = $injector.get('$q');
    var localStorageService: ng.local.storage.ILocalStorageService = $injector.get('localStorageService');

    return {
        request: (config: ng.IRequestConfig): ng.IRequestConfig => {
            // check if headers are present
            config.headers = config.headers || {};

            // the error was here! I was trying to add properties to config that I think angular was not expecting
            // removing this line solved the issue
            // if (!config.bypassToken) {

            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if (loggedUserInfo) {
                config.headers['Authorization'] = 'Bearer ' + loggedUserInfo.access_token;
            }
            return config;
        },
        responseError: (rejection)  => {
            // check if user is logged in
            var loggedUserInfo = localStorageService.get<models.LoggedUserInfoModel>('Auth');
            if ((rejection.status === 401) && (loggedUserInfo)) {

                // if so, then the user must login againd
                localStorageService.remove('Auth');
                $location.path('/home');
                console.error(rejection);
            }
            return $q.reject(rejection);
        }
    };
}]);