Check User exists in a Role in ASP.NET Identity 2.0

Read full post on Falafel blog

ASP.NET MVC5 uses Identity 2.0 to manage the users and their roles. There may be scenario to check whether the currently logged in user or any user with the id exists in the given role or not, and checking can be done either in the controller class or in any other class of the application.

Check for the currently logged in user
In a controller you can find whether the currently logged in user exist in a role or not by using User property of the controller class. Type of the User property is IPrincipal and it has a Boolean method IsInRole which takes the role name as input and returns true if the currently logged in user exist in the role.

Read full post on Falafel blog

Start-up code using WebActivator in MVC application

Read full post on Falafel blog

WebActivator allows us to execute a code long before application start-up. There may be requirements when you need to load external assemblies or instantiate a particular object before the application start up. You need to make sure some codes execute before the codes inside the App_Start folder and the global.asax file. To do this WebActivator should be used.
You can add the WebActivator package using NuGet.

Let us consider an example in an MVC application in which we want to call a method of a class before  the execution of the application. To do this follow the steps below:

  • Attribute the class with WebActivator
  • Pass the type of the class
  • Pass the name of the method to be executed

Read full post on Falafel blog

Seed the database with initial Users in MVC 5

 

Read full article on Falafel blog

In MVC 5 applications you may want to seed the database with initial users for various reasons. You may want default users and roles added as part of the application. In this post, we will take a look at how to  seed the database with default users.
The MVC 5 application uses ASP.Net Identity 2.0 to manage users, roles and identities. ASP.Net Identity 2.0 uses the Entity framework code first approach to create a database. To seed the database, first you need to enable migration on the database. To enable migration, in the package manager console run the command enable-migrations as shown below:

After successfully enabling migration you should find a Migrations folder in the solution explorer.

 

Read full article on Falafel blog

Custom Action Filter in ASP.NET MVC 5

Read full article on Falafel blog here

ASP.NET MVC 5 provides five different kinds of Filters. They are as follows:

  1. Authentication [Introduced in MVC5]
  2. Authorization
  3. Action
  4. Result
  5. Exception

Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied.

  • Authentication filter runs before any other filter or action method
  • Authorization filter runs after Authentication filter and before any other filter or action method
  • Action filter runs before and after any action method
  • Result filter runs before and after execution of any action result
  • Exception filter runs only if action methods, filters or action results throw an exception

Read full article on Falafel blog here

Convert User to ApplicationUser in ASP.Net MVC

In the last post I talked about How to get current user in ASP.Net MVC 5 . Type of the current user is IPrincipal which is shown as follows:

image

You may come across requirement to work with ApplicationUser which is created as follows:

image

You can covert returned User to ApplicationUser as follows:


ApplicationDbContext db = new ApplicationDbContext();
            ApplicationUser appUser = db.Users.FirstOrDefault(x => x.Id == userId);
            return appUser ;

To convert create instance of the ApplicationDBContext and then fetch user using LINQ to Entity. Returned user from context is of type ApplicationUser.

Hope it helps. Happy coding.

How to get current user in ASP.Net MVC 5

There are two simple ways to get current user in MVC 5. If you are inside the controller class current user can be fetched as follows,


string userId = User.Identity.GetUserId();

Do not forget to add namespace,

 


using Microsoft.AspNet.Identity;

Other scenario could be that you are not inside the controller class and want to fetch the user information. You can fetch that using HttpContext class.

HttpContext.Current.User.Identity.GetUserId();

I hope it helps. Happy Coding.

RedirectToAction or View as ActionResult in ASP .Net MVC5 ?

We have often seen action returns a View method. Optionally we can also pass the view name and the other parameters in the View method. Most of the time we return a view as ActionResult to navigate.



public ActionResult About()
        {
                    
            ViewBag.Message = "Your application description page.";
            return View();
        }

Now I have a requirement to navigate to Login view or return Login view on the basis of some authorization check. There are various ways you can do this however the approach I selected required me to override the OnActionExecuting() method in the controller class.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = View("Account/Login");
            }
            base.OnActionExecuting(filterContext);
        }

Type of the filter context result is ActionResult, so its value can be set to a View. To navigate I set the value of the filterContext.Result as View with view name as parameter.

Simple ? but it did not work, and I got the exception as follows:

imageKeep in mind that I am trying to navigate to the Login view which is part of the Account controller from Home controller. However If you are navigating to view from same controller, you won’t get the above exception. Essentially we are trying cross controller view navigation. To get rid of above exception, I had to use RedirectToAction().

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = RedirectToAction("Login", "Account");
            }
            base.OnActionExecuting(filterContext);
        }


Another difference is RedirectToRoute make another request and View returns HTML to render and it does not make new request. Conclusion is use RedirectToAction if you are doing cross controller navigation. Any other thought?

Happy coding.

Fetching Image from database in ASP.NET MVC 5 application

In this post we will learn to fetch image from a database. I have taken Northwind database as an example. Employee table of the Notrhwind database stores a Photo using the Image type. We will fetch data from the Photo column (type: Image) in the MVC application.

image

Let us start with the Controller. In the Index action all the Employees are fetched using the EmployeeRepository.


public ActionResult Index()
        {
            return View(_employeeRepository.List);
        }

Note: I am using repository pattern and the Entity framework. However you can fetch data directly using the Entity framework without the repository pattern.

In the View, you should convert fetched photo in a byte array as shown below. For normal photo you don’t need to subtract 78 from the length. However OLE photos it is required.


<td>
            @{ byte[] photo = item.Photo;
             string imageSrc = null;
             if (photo != null)
             {
                 MemoryStream ms = new MemoryStream();
                 ms.Write(photo, 78, photo.Length - 78);
                 string imageBase64 = Convert.ToBase64String(ms.ToArray());
                 imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
             }
            }           

            <img src="@imageSrc" alt="Image" />
        </td>

In above code snippet manually we are creating Memory Stream and then converting that to byte array. However in MVC library is available to do this task for you.

image

You can use Convert.ToBase64String() method to convert the fetched image into an encode string. This function is overloaded with four different set of parameters. I am passing byte array, offset value, length and format option to create the encoded string from the image byte array. So this approach can be replaced as follows:


  <td>

            <img src="data:image/png;base64,@Convert.ToBase64String(item.Photo,78,item.Photo.Length-78 ,
            Base64FormattingOptions.None)"
                 alt="Image" /> 

        </td>

You should able to view fetched images in the application. Happy coding.

Attribute Routing in ASP.NET MVC 5

ASP.NET MVC 5 introduced Attribute Routing. It allows you to apply a route directly on the controller class. Before we use the Attribute Routing, let’s relook how the convention based routing works.

We create a route as follows:

clip_image002

Index action of Home controller can be accessed on two different URLs. Either using the base URL (default value is set) or using baseurl/Home/Index as shown below:

clip_image004

In convention based routing action is accessed using the baseurl/controllername/actionname. Using the Attribute Routing this behaviour can be overridden. To use attribute routing you need to enable it in RouteConfig. To enable it, in the RoutConfig.cs call routes.MapMvcRouteAttribute() method.

clip_image006

Once it is enabled you can apply attribute routing on action using Route attribute and passing a value in this.

clip_image008

Now Index action can be access on the URL: baseurl/Test

clip_image010

You can also pass parameters in the attribute route. Parameters name and variables in route value must be the same.

clip_image012

Index action can be access with parameter values as shown below- I am passing 40 as value of age and steve as value of name.

clip_image014

You may want to use the attribute routing in your project as per the requirement. Keep in mind that attribute routing and the convention based routing can be used together.

Happy coding.

Customize the MVC 5 Application Users’ using ASP.Net Identity 2.0

Read full article on Falafel blog

In ASP.Net MVC 5.0, users and their roles are managed using ASP.Net Identity 2.0. By default when you create a new account email, password and confirm password are required as it’s shown below.

clip_image002

You may come across a requirement to modify the required fields for a particular application user. For example, along with the email and password, you want to save the user’s age, country and city. In this post we will learn to modify the user information. Basically there are the three steps involved in this:

image

Read full article on Falafel blog