Ale*_*scu 5 asp.net asp.net-mvc asp.net-web-api
在常规控制器中,以下代码有效:
[HttpPost]
public ActionResult Custom()
{
string name = User.Identity.GetUserName();
string id = User.Identity.GetUserId();
return Content(string.Format("Name:{0} </br> ID: {1}",name, id));
}
Run Code Online (Sandbox Code Playgroud)
在Web Api 2 Controller中,name和id字符串为空:
[HttpPost]
public IHttpActionResult Test()
{
string name = User.Identity.GetUserName();
string id = User.Identity.GetUserId();
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我为什么GetUserId()在普通控制器中工作但不在Api中工作?在这两种情况下我都登录,并被GlobalConfiguration.Configure(WebApiConfig.Register);添加Application_Start()进去Global.asax.cs.
我有另一个问题.如果我用[Authorize]属性装饰我的api控制器,我甚至无法访问我的api.当我已登录时,邮递员会将我引导至登录页面.
[[Authorize]]
public class TestController : ApiController
{
....
Run Code Online (Sandbox Code Playgroud)
string id = RequestContext.Principal.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)
当你有 ApiController 时尝试使用它。
| 归档时间: |
|
| 查看次数: |
3564 次 |
| 最近记录: |