使用新的ASP.NET Web API的Principal

Muh*_*hid 1 visual-studio .net-4.5 asp.net-web-api visual-studio-2012

前段时间我使用asp.net Web-api beta构建了API.我在某处读到,当在IIS中托管时,web-api从其运行的Web应用程序继承Identity.我的api也在网站上运行.使用beta二进制文件,当我登录该站点然后移动到http://localhost:4343/webui/api/values它时,将返回登录用户的正确值.这是Get值控制器的方法.

public IQueryable<string> Get()
        {
            var pr = Request.GetUserPrincipal();
            var username = Request.GetUserPrincipal().Identity.Name; //Null reference exception after installing vs 2012 here. Identity is null even though I am logged in 
            var values = GetUserValues(username);
            return values.AsQueryable();
        }
Run Code Online (Sandbox Code Playgroud)

它曾经与web-api的beta版本一起正常工作但是在vs2012的最终版本中它抛出了null引用异常.我已将网站转换为使用.net 4.5.知道这里发生了什么吗?

小智 5

ApiController现在有一个名为"User"的属性,它是IPrincipal.

var pr = User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)

在内部,User属性调用了tugberk提到的Thread.CurrentPrincipal.