简体   繁体   English

WebApi控制器生命周期

[英]WebApi Controller Lifecycle

So, here's the deal. 所以,这是交易。

I have a WebApi with a number of Controllers. 我有一个带有多个控制器的WebApi。 I have an Identity Server configured to to Authentication. 我将Identity Server配置为进行身份验证。 This all works. 所有这一切。

When I make a call on the API and I pass the appropriate token, if I put a breakpoint in any of the Actions of the Controller, the User object is properly populated. 当我调用API并传递适当的令牌时,如果我在Controller的任何Action中都设置了断点,则将正确填充User对象。

Now, the code that the API Actions execute needs data related to the authenticated user. 现在,API操作执行的代码需要与经过身份验证的用户有关的数据。 If I attempt to execute this code in the constructor of the Controller my code fails because User is not yet properly populated. 如果我尝试在Controller的构造函数中执行此代码,则代码将失败,因为用户尚未正确填充。

So, to my question: is there some element of the Controller's lifecycle, that I have yet to discover, that will allow me to execute code for every call on the Controller (like it would in the constructor) but where the User object has been properly populated? 因此,我的问题是:是否有Controller生命周期的某些元素尚未发现,这将允许我对Controller上的每个调用执行代码(就像在构造函数中一样),但是User对象位于何处正确地填充?

The User is only assigned well after the controller is created. 仅在创建控制器后才为用户分配好权限。 There are no events on ApiControllers that you can handle to do that. ApiControllers上没有可处理的事件。 The most common way to this is to extract a method that retrieves the extra information and call it in every action 最常见的方法是提取一种方法,该方法检索额外的信息并在每次操作中调用它

You can add some kind of token(encrypted UserId/Guid) in the header. 您可以在标头中添加某种令牌(加密的UserId / Guid)。 You can use the header variable/token to get the User object in the controller side. 您可以使用标头变量/令牌在控制器端获取User对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM