using Application.Domain.Entities; using Infrastructure.Data; using Infrastructure.Extensions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace UserCenter.Controllers { [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]/[action]")] [ApiController] public class UserController : ControllerBase { private readonly IRepository _userRepo; public UserController(IRepository userRepo) { this._userRepo = userRepo; } [HttpGet] [Authorize] public ActionResult GetUserInfo() { try { if (!User.Identity.IsAuthenticated) { ModelState.AddModelError("", "未登录"); return Unauthorized(ModelState); } var userName = User.Identity.Name; var model = this._userRepo.ReadOnlyTable() .Include(o => o.UserRoles) .ThenInclude(o => o.Role) .Where(o => o.UserName == userName) .ToList() .Select(o => new { o.UserName, o.RealName, o.IdCardNumber, o.NickName, o.Avatar, o.Sex, o.Birthday, o.Email, o.PhoneNumber, Roles = o.UserRoles.Select(o => o.Role.Name) }) .FirstOrDefault(); if (model == null) { ModelState.AddModelError("", "用户不存在"); return BadRequest(ModelState); } return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } } }