Global variable in Web API

和自甴很熟 提交于 2019-12-11 12:57:54

问题


I have a Web API application that is authenticated using a combination of userid and an APIKey as part of the RequestMessage. In my authorization filter I check if the combination is valid before proceeding. I then need to use the userid to log some actions in my controllers.

The UserID and key are encoded together. Something like: .../api/v1/Transaction?api_key=YmFyZGFnYWR2ZXJndXI

The problem I am having is how to expose the userid to the controller.


回答1:


Using the comment from Chips_100 I added CurrentUserId to my Controller and then this code to my AuthFilter:

public class CustomAuthFilter : AuthorizeAttribute
{
    private BaseController controller;
    public override void OnAuthorization(HttpActionContext actionContext)
    {   
        controller = actionContext.ControllerContext.Controller as BaseController;
        //Some code ommitted for clarity
        if (controller != null)
            controller.CurrentUserId = userAccount[0];
    }
}

Seems to work perfectly so far.



来源:https://stackoverflow.com/questions/37026394/global-variable-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!