0
我的另一个问题,耶!Web Api User.Identity.Name
好了,我有这样的代码:
public class TokenMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = request.Headers.GetValues("Authorization-Token").FirstOrDefault();
if (String.IsNullOrEmpty(token))
return Task<HttpResponseMessage>.Factory.StartNew(() =>
{
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Missing Authorization-Token")
};
});
try
{
var user = UserRepository.GetUsers().FirstOrDefault(x => x.UserName == RSAClass.Decrypt(token));
if (user == null)
return Task<HttpResponseMessage>.Factory.StartNew(() =>
{
return new HttpResponseMessage(HttpStatusCode.Forbidden)
{
Content = new StringContent("Unauthorized User")
};
});
var identity = new GenericIdentity(user.UserName);
var principal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
HttpContext.Current.User = principal;
}
catch (RSAClass.RSAException)
{
return Task<HttpResponseMessage>.Factory.StartNew(() =>
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Error encountered while attempting to process authorization token")
};
});
}
return base.SendAsync(request, cancellationToken);
}
}
和它完美的作品。 如果我把我的使用jQuery的,像这样的API:
function GetAllCategories() {
var credentials = '@ViewBag.encrypted';
$.ajax({
url: "http://localhost:18904/api/Categories",
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization-Token", credentials);
},
success: function (data) {
$.each(data, function (i, category) {
var row = '<tr><td>' + category.DisplayName + '</td><td>' + category.DateCreated + '</td><td>' + category.AssetCount + '</td><td>' + category.CategoryCount + '</td></tr>';
$('#categories').append(row);
});
},
error: function() {
alert('error');
}
});
}
我得到类别的一个很好的列表。高手。 现在您可以看到我正在设置CurrentPrincipal和Current.User。 在我的CategoriesController我有访问我的User.Identity这是伟大的。
我的问题是这样的: 我有我自己的配置文件,它有很多其他信息存储在它中,所以通用的MembershipUser是不够的。所以我怎样才能设置我的个人资料,以便它会持续。例如,我想设置一些将保留在MessageHandler中的设置,例如设置HttpContext.Current.User或Thread.CurrentPrincipal。
任何人都可以帮我一把吗?
干杯,
/r3plica