User.Identity 基于使用相同标记的方法调用不同
User.Identity different based on method call with same token
在尝试 ASP.NET Identity 后,我遇到了一些我不理解的行为。我在 VS 2015 中选择了 Web API 选项,这会为您创建一个 AccountController.cs。我添加了自己的控制器并遇到了 User.Identity 对象的问题。当我调用 /api/Account/IsAuthenticated 时,User.Identity
对象不包含令牌信息。方法如下所示:
[AllowAnonymous]
[HttpGet]
[Route("IsAuthenticated")]
public bool IsAuthenticated()
{
return User.Identity.IsAuthenticated;
}
在我的另一个控制器 CategoryController.cs 中,我有一个监听 /Category/GetAllCategories
的方法,如下所示:
[HttpPost]
public ActionResult GetAllCategories()
{
var userId = User.Identity.GetUserId();
return Json(Category.GetAllCategories(userId), JsonRequestBehavior.AllowGet);
}
现在奇怪的是,在 GetAllCategories 中,我的用户对象包含来自令牌的正确信息。两种方法我提出请求的方式是一样的。只有 url 不同。
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
function test(){
$.ajax({
datatype: "json",
type: "POST",
url: baseurl + "/api/Account/IsAuthenticated",
headers: headers})
.done(function (data) { console.log(data); })
.fail(function (data) { console.log("fail"); console.log(data); });
}
我的问题: 为什么我的 AccountController 中的 User.Identity 是空的?
不太确定正确答案需要哪些信息。如果您需要更多信息,请随时询问。
[AllowAnonymous]
这会导致请求使用匿名。删除它并重试。
我的 Startup.cs
有问题。它看起来像这样:
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
//ConfigureAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
ConfigureAuth(app);
}
我不得不将 ConfigureAuth(app)
移到 app.UseWebApi(config)
上方。仍然不明白为什么这解决了它。有人可以解释为什么这会有所作为吗?
在尝试 ASP.NET Identity 后,我遇到了一些我不理解的行为。我在 VS 2015 中选择了 Web API 选项,这会为您创建一个 AccountController.cs。我添加了自己的控制器并遇到了 User.Identity 对象的问题。当我调用 /api/Account/IsAuthenticated 时,User.Identity
对象不包含令牌信息。方法如下所示:
[AllowAnonymous]
[HttpGet]
[Route("IsAuthenticated")]
public bool IsAuthenticated()
{
return User.Identity.IsAuthenticated;
}
在我的另一个控制器 CategoryController.cs 中,我有一个监听 /Category/GetAllCategories
的方法,如下所示:
[HttpPost]
public ActionResult GetAllCategories()
{
var userId = User.Identity.GetUserId();
return Json(Category.GetAllCategories(userId), JsonRequestBehavior.AllowGet);
}
现在奇怪的是,在 GetAllCategories 中,我的用户对象包含来自令牌的正确信息。两种方法我提出请求的方式是一样的。只有 url 不同。
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
function test(){
$.ajax({
datatype: "json",
type: "POST",
url: baseurl + "/api/Account/IsAuthenticated",
headers: headers})
.done(function (data) { console.log(data); })
.fail(function (data) { console.log("fail"); console.log(data); });
}
我的问题: 为什么我的 AccountController 中的 User.Identity 是空的?
不太确定正确答案需要哪些信息。如果您需要更多信息,请随时询问。
[AllowAnonymous]
这会导致请求使用匿名。删除它并重试。
我的 Startup.cs
有问题。它看起来像这样:
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
//ConfigureAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
ConfigureAuth(app);
}
我不得不将 ConfigureAuth(app)
移到 app.UseWebApi(config)
上方。仍然不明白为什么这解决了它。有人可以解释为什么这会有所作为吗?