Can I access IIdentity from Web API

后端 未结 4 1931
有刺的猬
有刺的猬 2020-12-25 09:45

I\'m adding some Web API services to an existing MVC application. I have a model binder for my MVC controllers to get the user object stored in a CustomIdentity. I\'m tryi

相关标签:
4条回答
  • 2020-12-25 10:29

    You can try to use this extension method from System.ServiceModel.dll:

    public static IPrincipal GetUserPrincipal(this HttpRequestMessage request);
    

    as:

    IPrincipal principal = request.GetUserPrincipal();
    IIdentity identity = principal.Identity;
    
    0 讨论(0)
  • 2020-12-25 10:32

    I had the same problem and I found this way. In your ApiController you can use
    base.ControllerContext.RequestContext.Principal.Identity.;

    0 讨论(0)
  • 2020-12-25 10:43

    They removed GetUserPrincipal in ASP.NET MVC 4 RC. However it seems the ApiController property User has replaced this: http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.user

    0 讨论(0)
  • Yes you can. ApiController has a Request property of type System.Net.Http.HttpRequestMessage; this holds details about the current request naturally (it also has a setter for unit testing purposes). HttpRequestMessage has a Properties dictionary; you will find the value of the key MS_UserPrincipal holds your IPrincipal object.

    In researching this answer, I came across the System.Web.Http.HttpRequestMessageExtensions which has a GetUserPrincipal(this HttpRequestMessage request) extension method which accesses this dictionary value; I hadn't seen this extension method before and was accessing Request.Properties["MS_UserPrincipal"] directly, but this might be a better method (less dependent on the ASP.NET Web Api team keeping the name of the key the same...)

    0 讨论(0)
提交回复
热议问题