我使用此代码创建了一些声明,我在登录应用程序时获取了值。我想在我的一些api控制器中使用声明值“Id”,
[Authorize]
[Route("api/banners/{customerId")]
[HttpGet]
public HttpResponseMessage GetBanners(int customerId)
{
return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}
var ticket = new AuthenticationTicket(identity,props); context.Validated(票);
所以在控制器中我有这个代码:
[Authorize]
[Route("api/banners")]
[HttpGet]
public HttpResponseMessage GetBanners()
{
int CustomerId = SOME FUNCTION THAT GETS THE CLAIM VALUE I WANT (ID)
return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}
我想将代码更改为此代码:
SELECT time, air FROM pi_sensors_network
WHERE date BETWEEN '".$date1."' AND '".$date2."'"
AND location = '".$location."'";
我一直在研究,但我刚刚找到了AuthorizationFilterAttribute,但它只是在路线上使用它,有没有办法让你知道我可以建立这个功能,所以我只是在控制器中调用它?
我正在使用Microsoft.AspNet.Identity.Owin 2.0.0
感谢您的帮助
答案 0 :(得分:6)
保存您的自定义声明:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("Id", user.Id.ToString()));
得到这样的结果:
((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "Id").Value