如何在ASP.Net Web API控制器中找到用户的名称?

时间:2013-07-09 08:17:25

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

以下是我的控制器的一些示例代码:

public class ContentController : ApiController
{
    private IContentService _contentService;

    public ContentController(
        IContentService contentService)
    {
        _contentService = contentService;
    }

    // GET api/Content/5
    [HttpGet]
    [ActionName("GetContent")]
    public Content GetContent(int Id)
    {
        Content content = _uow.Contents.GetById(Id);
        if (content == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return content;
    }

我想找到用户的ID。谁能告诉我怎么做到这一点?我正在使用标准的ASP.NET简单身份验证,我使用ASP.NET MVC帐户控制器登录我的用户。

2 个答案:

答案 0 :(得分:2)

由于您使用的是表单身份验证,因此可以尝试使用HttpContext类和Identity属性:

var currentUser = HttpContext.User.Identity;

答案 1 :(得分:0)

在api控制器中,您只需使用:

User.Identity.Name  

检查

User.Identity.IsAuthenticated

第一