Wednesday, 22 April 2015

What's New in ASP.NET MVC 5

 What is the difference between each version of MVC 2, 3 , 4, 5 and 6?

MVC 6

  • ASP.NET MVC and Web API has been merged in to one. 
  • Dependency injection is inbuilt and part of MVC. 
  • Side by side - deploy the runtime and framework with your application 
  • Everything packaged with NuGet, Including the .NET runtime itself. 
  • New JSON based project structure. 
  • No need to recompile for every change. Just hit save and refresh the browser. 
  • Compilation done with the new Roslyn real-time compiler. 
  • vNext is Open Source via the .NET Foundation and is taking public contributions. 
  • vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

MVC 5

  • One ASP.NET 
  • Attribute based routing 
  • Asp.Net Identity 
  • Bootstrap in the MVC template 
  • Authentication Filters 
  • Filter overrides  

MVC 4

  • ASP.NET Web API 
  • Refreshed and modernized default project templates 
  • New mobile project template 
  • Many new features to support mobile apps 
  • Enhanced support for asynchronous methods

MVC 3
  • Razor 
  • Readymade project templates 
  • HTML 5 enabled templates 
  • Support for Multiple View Engines 
  • JavaScript and Ajax 
  • Model Validation Improvements

MVC 2
  • Client-Side Validation 
  • Templated Helpers
  • Areas 
  • Asynchronous Controllers 
  • Html.ValidationSummary Helper Method 
  • DefaultValueAttribute in Action-Method Parameters 
  • Binding Binary Data with Model Binders 
  • DataAnnotations Attributes 
  • Model-Validator Providers 
  • New RequireHttpsAttribute Action Filter 
  • Templated Helpers 
  • Display Model-Level Errors 

New features: in MVC5

1.You can customize your MVC project and configure authentication using the One ASP.NET project creation wizard.

There is one option Change Authentication button by clicking this button we can customise authentication as shown below.

2.ASP.NET Identity:

The MVC project templates have been updated to use ASP.NET Identity for authentication and identity management.Some of the main features of ASP.NET Identity are
  • It can be used by any ASP.NET framework such as ASP.NET MVC and WebForms.
  • We can easily add third party authentication providers like google , facebook 
  • We have control of the persistence storage.So we can now store the credentials not only in the SQL Server database but can also use other persistence storages like Azure and NoSQL databases.

Third party authentication providers like google , facebook

In the New ASP.NET Project dialog, click MVC. If the Authentication is not Individual User Accounts, click theChange Authentication button and select Individual User Accounts.
Use the NuGet package manager to update the OWIN middleware. Select Updates in the left menu. You can click on the Update All button or you can search for only OWIN packages (shown in the next image):


                                                           (or)

From the Package Manager Console (PMC), you can enter the Update-Package command, which will update all packages.if you want to install dependencies related to Google only then
use install- Package Microsoft.Owin.Security.Google

Setting up SSL in the Project:

  To connect to authentication providers like Google and Facebook, you will need to set up IIS-Express to use SSL. It's important to keep using SSL after login and not drop back to HTTP, your login cookie is just as secret as your username and password, and without using SSL you’re sending it in clear-text across the wire. Besides, you’ve already taken the time to perform the handshake and secure the channel (which is the bulk of what makes HTTPS slower than HTTP) before the MVC pipeline is run, so redirecting back to HTTP after you’re logged in won’t make the current request or future requests much faster.
  1. Hit the F4 key to show the project properties. Alternatively, from the View menu you can select Properties Window.
  2. Change SSL Enabled to True.
Select the Web tab, and then paste the SSL URL into the Project Url box. Save the file (Ctl+S). You will need this URL to configure Facebook and Google authentication apps.
Add the RequireHttps attribute to the Home controller to require all requests must use HTTPS. A more secure approach is to add the RequireHttps filter to the application.

Creating a Google app for OAuth 2 and connecting the app to the project
  1. Navigate to the Google Developers Console.
  2. Click the Create Project button and enter a project name and ID (you can use the default values). In a few seconds the new project will be created and your browser will display the new projects page.
  3. In the left tab, click APIs & auth, and then >  Credentials.
  4. Click the Create New Client ID under OAuth.
    1. In the Create Client ID dialog, keep the default Web application for the application type.
    2. Set the Authorized JavaScript origins to the SSL URL you used above (https://localhost:44300/ unless you've created other SSL projects)
    3. Set the Authorized redirect URI to:
           https://localhost:44300/signin-google
  5. Click the Consent screen menu item, then set your email address and product name. When you have completed the form click Save.
  6. Click the APIs menu item
Copy and paste the AppId and App Secret into the UseGoogleAuthentication method.


Now if we run the application and go to the login page we can see the below page.


On clicking Google button we are redirected to the following screen where user name and password can be entered.


The google authentication is enabled since we used the UseGoogleAuthentication() method. Similarly we can use the authentication methods for Microsoft and other social sites. So using ASP.NET Identity it's just a matter of making a method call to use third party authentication.

3.Bootstrap:
The MVC project template has been updated to use Bootstrap to provide a sleek and responsive look and feel that you can easily customize.

 4.Attribute based routing:
The earlier style of routing, called convention-based routing(Routing in MVC), is still fully supported. In fact, you can combine both techniques in the same project.
Using attribute based routing we can define the route in the same place where action method is defined. Following is an example of a route defined using the Route attribute. As you can see the route is directly attached to the action method.

  [Route("Products/Electronics/{id}")]
       public ActionResult GetElectronicItems(string id)
       {
           ViewBag.Id = id;
            return View();
       }     
To enable attribute based routing we need to add the following in the RouteConfig file.
 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapMvcAttributeRoutes();
        }  



So now we have attached the Route attribute to our action method our action method will be able to handle the requests which matches the URL pattern defined by the Route attribute.
Optional Parameter

We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the“?” character.

If the above action method is called and and the value for “id” parameter is not provided we will get an exception since id is a required parameter. We can make it an optional parameter by making the following changes.

  [Route("Products/Electronics/{id?}")]
        public ActionResult GetElectronicItems(int? id) { 
            ViewBag.Id = id; return View(); 
        }    


Note that we have made id an optional parameter by using “?”.Also since id is a value type we have to make it nullable type since we always need to provide values for value type parameters as they cannot have null values.
Route constraints

We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following
 [Route("Products/Electronics/{id:int}")] 


5.Authnetication Filter in MVC5: Filters in MVC

Filters are used to perform logic either before an action method is called or after an action method runs. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behaviour to controller action methods.

Prior to ASP.NET MVC 5, there are 4 types of filters: 


Authorization filters (IAuthorizationFilter)
Action filters (IActionFilter)
Result filters (IResultFilter)
Exception filters (IExceptionFilter)

Prior to ASP.NET MVC 5 we are using the [Authorization] attribute to enforce role-based security within the ASP.NET MVC applications. ASP.NET MVC 5 introduces the new Authentication filters (IAuthenticationFilter).

Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. Authentication filters process credentials in the request and provide a corresponding principal. Authentication filters can also add authentication challenges in response to unauthorized requests.

The reason for introducing authentication filters is to separate authentication from authorization (authentication first, then authorization):
Authentication is for establishing a principal for current request
Authorization is to verify whether or not the current principal is permitted to execute current request


We can use the IAuthenticationFilter (System.Web.Mvc.Filters) to create a custom authentication filter. Here is the definition of IAuthenticationFilter: namespace System.Web.Mvc.Filters { public interface IAuthenticationFilter { void OnAuthentication(AuthenticationContext filterContext); void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext); } }

IAuthenticationFilter interface provides two methods:
OnAuthentication(AuthenticationContext filterContext)
This method is used to authenticates the request & it provides the context to use for authentication.
OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
This method adds an authentication challenge to the current ActionResult & it provides the context to use for the authentication challenge.

We can use authentication filters to allow users to authenticate to the application from various third-party vendors (facebook, linkedin, twitter etc…) or a custom authentication provider.

If look into real implementation details by comparing IAuthorizationFilter &IAuthenticationFilter, IAuthenticationFilter’s OnAuthentication(…) method hasAuthenticationContext parameter which has Principal object.

When ControllerActionInvoker class InvokeAction() method is executed to Invoke an Action method, first it will iterate through the all Authentication filters OnAuthentication() methods. Then replace the original Principal object on the HttpContext in case if the Principal is changed by Authentication filters OnAuthentication() method.

protected virtual AuthenticationContext InvokeAuthenticationFilters(ControllerContext controllerContext, 
                                    IList<IAuthenticationFilter> filters, 
                                    ActionDescriptor actionDescriptor)
{
   if (controllerContext == null)
     throw new ArgumentNullException("controllerContext");

   IPrincipal user = controllerContext.HttpContext.User;

   AuthenticationContext filterContext = new AuthenticationContext(controllerContext, 
                                    actionDescriptor, user);

   foreach (IAuthenticationFilter authenticationFilter in (IEnumerable<IAuthenticationFilter>) filters)
   {
     authenticationFilter.OnAuthentication(filterContext);
     if (filterContext.Result != null)
       break;
   }

   IPrincipal principal = filterContext.Principal;

   if (principal != user)
   {
     filterContext.HttpContext.User = principal;
     Thread.CurrentPrincipal = principal;
   }

   return filterContext;
}
 
This is give us ability to modify the original Principal object using authentication filter’s. Here is the story with OnAuthenticationChallenge() method.
protected virtual AuthenticationChallengeContext 
                InvokeAuthenticationFiltersChallenge(ControllerContext controllerContext, 
                                          IList<IAuthenticationFilter> filters, 
                                          ActionDescriptor actionDescriptor, ActionResult result)
{
  AuthenticationChallengeContext filterContext = new AuthenticationChallengeContext(controllerContext, 
                                                   actionDescriptor, result);

   foreach (IAuthenticationFilter authenticationFilter in (IEnumerable<IAuthenticationFilter>) filters)
       authenticationFilter.OnAuthenticationChallenge(filterContext);

  return filterContext;
}


No comments:

Post a Comment