Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Get UserId() Method From ASP.NET Identity Directly in Razor

I've this issue with Custom Authorization some parts of my Views (which i don't want to put on PartialView), instead I am using If statement like below:

@if (item.CurrentComment.Id == Guid.Parse(ViewBag.UserId) || repository.IsUserInRoles(Guid.Parse(ViewBag.UserId),"Manager") )
{
    <dd>
        <a href="@Url.Action("EditComment", "Ticketing",new { id = item.CurrentComment.Id, ticketId = Model.Tickets.CurrentTicket.Id })" class="btn btn-primary btn-sm" data-toggle="tooltip" data-placement="left">Edit</a>
    </dd>
    <dd>
        <a href="@Url.Action("RemoveComment", "Ticketing",new { id = item.CurrentComment.Id, ticketId = Model.Tickets.CurrentTicket.Id })" class="btn btn-danger btn-sm" data-toggle="tooltip" data-placement="left">Remove</a>
    </dd>
}

At the moment I get my UserId in my controller and pass it over with a ViewBag like below:

ViewBag.UserId = User.Identity.GetUserId(); 

I wondered how to call the GetUserId method directly in a razor so that I won't send it with a ViewBag anymore. I've tried using User.Identity. but the Method is Unknown there, which I assume it doesn't know the extension. Is there a way around it?

like image 323
Masoud Andalibi Avatar asked Feb 20 '17 11:02

Masoud Andalibi


People also ask

How can we get current logged in user in asp net core identity?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How do I get current user in Blazor?

There are three possibilities for getting the user in a component (a page is a component): Inject IHttpContextAccessor and from it access HttpContext and then User ; need to register IHttpContextAccessor in Startup. ConfigureServices , normally using AddHttpContextAccessor .


3 Answers

Just wanted to add my take as both of the above responses didn't work for me.

@using Microsoft.AspNetCore.Identity

@inject UserManager<IdentityUser> userManager

@if (project.CreatorId == userManager.GetUserId(User))
{
  //do something
}

I added

@using Microsoft.AspNetCore.Identity
@inject UserManager<IdentityUser> userManager 

to _ViewImports.cshtml because I need to use it in several views.

like image 80
Howard Choi Avatar answered Oct 21 '22 02:10

Howard Choi


This answer and question are for ASP.NET MVC 5,not ASP.NET CORE

Add the following using statement at the top of your view file.

using Microsoft.AspNet.Identity;

Following this, you should be able to use User.Identity.GetUserId()

like image 39
ColinM Avatar answered Oct 21 '22 02:10

ColinM


If somebody is looking for an ASP.NET Core solution (as I was an hour ago), there is a solution for you:

@using Microsoft.AspNetCore.Identity

var user = await UserManager.GetUserAsync(User);
var userId = user?.Id;
like image 42
Grigory Zhadko Avatar answered Oct 21 '22 03:10

Grigory Zhadko