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?
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
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 .
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.
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()
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With