如何在Web Api 2中使用User.Identity.GetUserId()

时间:2017-08-15 17:51:41

标签: entity-framework asp.net-mvc-5 asp.net-web-api2

我正在使用一个post方法,其中comedyId来自请求的正文,而使用postman我甚至在登录后一次又一次地被重定向到登录页面。

为什么登录不适用于Api和User.Identity.GetUserId()也返回空值?

 namespace ComedyCentral.Controllers.Api
    {
        [Authorize]
        public class AttendancesController : ApiController
        {
            private ApplicationDbContext _context;

            public AttendancesController()
            {
                _context = new ApplicationDbContext();
            }

            [HttpPost]
            public IHttpActionResult Attend([FromBody] int comedyId)
            {
                var userId = User.Identity.GetUserId();


                if (_context.Attendances.Any(a => a.AttendeeId == userId && a.ComedyId == comedyId))
                    return BadRequest("The attendance already exists.");

                var attendance = new Attendance
                {
                    ComedyId = comedyId,
                    AttendeeId = userId
                };
                _context.Attendances.Add(attendance);
                _context.SaveChanges();

                return Ok();
            }
        }
    }

0 个答案:

没有答案