问题描述:API控制器没有正确返回User.Identity的声明。
解决方法:
[Authorize]
public class UserController : ApiController
{
// ...
}
[Authorize]
public class UserController : ApiController
{
public IHttpActionResult GetUserInfo()
{
var userName = User.Identity.Name;
// ...
}
}
[Authorize(Roles = "Admin")]
public class UserController : ApiController
{
// ...
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 配置身份验证
app.UseAuthentication();
// ...
}
}
// 自定义身份验证逻辑示例
public static class CustomAuthentication
{
public static bool Authenticate(string username, string password)
{
// 身份验证逻辑
// ...
// 设置用户身份信息
var identity = new GenericIdentity(username);
// 添加用户角色
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
// 设置用户身份
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[] { "Admin" });
return true;
}
}
在需要进行身份验证的地方调用自定义身份验证逻辑。
if (CustomAuthentication.Authenticate(username, password))
{
// 身份验证通过
}
总结:确保在API控制器中正确配置了身份验证特性和相关的配置,以及在控制器的方法中正确使用User.Identity来获取用户身份信息。如果仍然出现问题,可以检查身份验证配置和提供程序的设置,以及自定义身份验证逻辑的正确性。