ASP.NET Core Identity - get current user

前端 未结 7 680
灰色年华
灰色年华 2020-12-07 11:48

To get the currently logged in user in MVC5, all we had to do was:

using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
             


        
7条回答
  •  轮回少年
    2020-12-07 12:37

    In .NET Core 2.0 the user already exists as part of the underlying inherited controller. Just use the User as you would normally or pass across to any repository code.

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "TENANT")]
    [HttpGet("issue-type-selection"), Produces("application/json")]
    public async Task IssueTypeSelection()
    {
        try
        {
            return new ObjectResult(await _item.IssueTypeSelection(User));
        }
        catch (ExceptionNotFound)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new
            {
                error = "invalid_grant",
                error_description = "Item Not Found"
            });
        }
    }
    

    This is where it inherits it from

    #region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
    // C:\Users\BhailDa\.nuget\packages\microsoft.aspnetcore.mvc.core\2.0.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll
    #endregion
    
    using System;
    using System.IO;
    using System.Linq.Expressions;
    using System.Runtime.CompilerServices;
    using System.Security.Claims;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Net.Http.Headers;
    
    namespace Microsoft.AspNetCore.Mvc
    {
        //
        // Summary:
        //     A base class for an MVC controller without view support.
        [Controller]
        public abstract class ControllerBase
        {
            protected ControllerBase();
    
            //
            // Summary:
            //     Gets the System.Security.Claims.ClaimsPrincipal for user associated with the
            //     executing action.
            public ClaimsPrincipal User { get; }
    

提交回复
热议问题