Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Page.User.Identity.Name in MVC3

In MVC2 I have used Page.User.Identity.Name using the <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

How can I use the same in MVC3?

like image 788
learning Avatar asked Jan 06 '11 10:01

learning


People also ask

What is HttpContext user?

The User property provides programmatic access to the properties and methods of the IPrincipal interface. Because ASP.NET pages contain a default reference to the System. Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .

How can I get UserName in MVC?

to get the current user name, however if you want to see all users record then you need to get the username by using its id, you can do this operation by joining Users table on user.id key or you can use it in View by having a method that take user id as parameter and return its Name.

How do I log into MVC identity with email instead of UserName?

cs change the property Email to UserName , remove the [EmailAddress] annotation from there and change the [Display(Name = "Email")] to [Display(Name = "Login")] or something you want to display. If you want to keep Email property, then add UserName property to the same view model and make it as required.

How authentication and authorization work in ASP.NET MVC?

Windows Authentication is used in conjunction with IIS authentication. The Authentication is performed by IIS in one of three ways such as basic, digest, or Integrated Windows Authentication. When IIS authentication is completed, then ASP.NET uses the authenticated identity to authorize access.


2 Answers

You can always do something like:

@Html.ViewContext.HttpContext.User.Identity.Name

but don't.

Normally a view shouldn't try to fetch such information. It is there to display whatever information is passed by the controller. It should be strongly typed to a model class which is passed by a controller action.

So in the controller action rendering this view:

[Authorize]
public ActionResult Index()
{
    var model = new MyViewModel
    {
        Username = User.Identity.Name
    }
    return View(model);
}

Now inside the view feel free to use this information:

@Model.Username
like image 121
Darin Dimitrov Avatar answered Sep 28 '22 07:09

Darin Dimitrov


MVC 2

<%: this.Page.User.Identity.Name %>

MVC 3

@this.User.Identity.Name
like image 28
Nikita Ignatov Avatar answered Sep 28 '22 07:09

Nikita Ignatov