Javascript 如何在标头中传递令牌并在cs中检索值
如何在头中传递令牌并在cs控制器中检索令牌的值?我在javascript中使用了以下代码Javascript 如何在标头中传递令牌并在cs中检索值,javascript,angularjs,asp.net-mvc,Javascript,Angularjs,Asp.net Mvc,如何在头中传递令牌并在cs控制器中检索令牌的值?我在javascript中使用了以下代码 $http({ url: vUrl+"Category/InsertCategories", dataType: 'json', method: 'POST', data: cats, params: { CompanyId: vCompanyId}, headers: { "Authen
$http({
url: vUrl+"Category/InsertCategories",
dataType: 'json',
method: 'POST',
data: cats,
params: { CompanyId: vCompanyId},
headers: {
"Authentication": "JsonToken",
"Content-Type": "application/json"
}
在请求中设置
授权
标题,如下所示:
headers: {
'Authorization': 'Bearer JsonToken'
}
并在控制器中检索令牌:
var token = HttpContext.Request.Headers["Authorization"];
通过多种方式设置授权标头 1: 2:
如果您使用的是angular 1.x,那么下面的内容将为您提供一些想法
yourAngularAppName.service('AuthenticationHeaderInterceptor', [
'$q',
'$location',
function(<dependencies if there are any>) {
var self = this;
config.headers['Authentication'] = "....";
return this; // or whatever you want
}
]);
yourAngularAppName.config([
'$httpProvider',
function(
$httpProvider
) {
// If you have token available at this time, you can do this as well instead of writing interceptor.
//$httpProvider.defaults.headers.common["Authentication"] = "....";
$httpProvider.interceptors.push('AuthenticationHeaderInterceptor');
}
]);
您的令牌是自定义令牌还是由任何云服务生成的令牌是自动生成的。因为它是身份验证标头,并且将用于几乎所有对C#MVC的调用,所以我会在angular中编写拦截器(编写服务,并附加到$httpProvider.interceptors集合),从而注入这些令牌。在MVC端,每个控制器都有Request属性(this.Request.Headers.GetValues(“Authentication”)。您使用的是哪个角度版本?非常感谢您的建议。使用上面提到的if-else条件解决了这个问题。@vidya,那么为什么您将答案标记为无用?
$.ajax({
type: 'GET/POST',
url: 'url',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + "JosnToke";
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
yourAngularAppName.service('AuthenticationHeaderInterceptor', [
'$q',
'$location',
function(<dependencies if there are any>) {
var self = this;
config.headers['Authentication'] = "....";
return this; // or whatever you want
}
]);
yourAngularAppName.config([
'$httpProvider',
function(
$httpProvider
) {
// If you have token available at this time, you can do this as well instead of writing interceptor.
//$httpProvider.defaults.headers.common["Authentication"] = "....";
$httpProvider.interceptors.push('AuthenticationHeaderInterceptor');
}
]);
public ActionResult TestAction()
{
var authenticationHeaders = this.Request.Headers.GetValues("Authentication");
var authHeader = authenticationHeaders?.FirstOrDefault(vt => vt != "null");
if (string.IsNullOrWhiteSpace(authHeader))
{
// return unauthorized
}
else {
// continue with rest of the stuff.
}
}