European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 5 Hosting - UK :: How to Use jQuery DatePicker for MVC

clock December 11, 2014 08:38 by author Scott

For those of you using ASP.NET MVC and hoping to receive a little guidance on how to implement a jQuery UI DatePicker widget on a date input field, as well as the appropriate way to pass dates from the view back to the controller,  the following article is just for you.

The first gotcha was to download the entire jQuery UI (Combined Library) package from Nuget.  Downloading the older jQuery UI DatePicker package has some incompatibilities with the jQuery core framework that the bootstrap template needs to function correctly.

The next step is to extend the model you are using to support a datetime field you’d like to manage with the jQuery UI DatePicker. Take a look at the DateOfBirth field in the code below.

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; } 

    [Required]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; } 

    [Required]
    [Display(Name = "Date of Birth")]
    public DateTime DateOfBirth { get; set; }

Extending the view to support this datetime field is pretty straight forward razor coding. The one thing to notice in this piece of code is the “datefield” css class used in the TextBoxFor method. We’ll be using the class later on to allow for easier jQuery UI DatePicker widget initialization. It also allows for more reusability across your applications.

<div class="form-group">
    @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.DateOfBirth, new { @class = "form-control datefield" })
    </div>
</div>

The code to initialize any jQuery UI DatePicker widgets is only 3 lines of code. We utilize the “datefield” css class here as a generic selector so all input fields with this class will transform into jQuery UI DatePicker widgets.

$(function () {
    $(".datefield").datepicker();
});

The final touch is to include all required .js and .css files necessary to a common layout which provides this codes use throughout your web application.  If you are concerned about page load times you can cherry pick where you’d like these includes to go.

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

        </footer>
    </div> 

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap") 

    <link href="~/Content/themes/base/jquery.ui.core.css" rel="stylesheet" />
    <link href="~/Content/themes/base/jquery.ui.datepicker.css" rel="stylesheet" />
    <link href="~/Content/themes/base/jquery.ui.theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-ui-1.10.4.js"></script>
    <script src="~/Scripts/Common/DatePickerReady.js"></script> 

    @RenderSection("scripts", required: false)
</body>
</html>

The nice thing about this approach is that ASP.NET MVC5 takes care of all the model binding for you since the jQuery UI DateTime picker sets the input field as a valid date value that native model binding understands. By the time you get to your controller you’ll have your datetime value set.

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            var message = new EmailMessage();
            message.ToEmail = model.EmailAddress;
            message.Subject = "Insurance Website Registration";
            message.IsHtml = false;
            message.Body =
                String.Format("You have succesfully registered for Vanderbuilt Insurance with the following" +
                              "username: {0}", model.UserName); 

            var status = EmailService.SendEmailMessage(message); 

            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    } 

    // If we got this far, something failed, redisplay form
    return View(model);
}



European ASP.NET MVC 4 Hosting - France :: Configuring Custom Membership and Role Provider using ASP.NET MVC4

clock December 4, 2014 07:25 by author Scott

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.

You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

In tis tutorial, we are going to implement and configure a custom Membership Provider using ASP.NET MVC4

Create Custom MemberShip Application class Library

1. Create a class Library Project (our sample Projet name isLogCorner.SoftwareStore.Security)

Reference the assembly  System.Web.ApplicationServices (Right Click Reference => Add reference => Select Assemblies => navigate toSystem.Web.ApplicationServices and add it)

2. Create a Class CustomMembershipProvider and derive it fromMembershipProvider

3. Override ValidateUser as follow

Create ASP.NET MVC 4 Application Client

1. Create an ASP.NET MVC4 application Client ( Add New projet => ASP.NETMVC4 Web Application => Select Template Internet Web Appliction and Click OK)

2. Open Web.config file

3. Add or Replace membership section as follow

4. Open HomeController and Authorize Attribute to Index ActionResult

5. Run the application ASP.NET MVC4 application Client,  you ll have the errors below

6. If you see the above error, then execute this command:

<add key= »enableSimpleMembership » value= »false »/>
<add key= »autoFormsAuthentication » value= »false »/>

7. Run the application ASP.NET MVC4 application Client,  you ll have another error

8. To fix it Open AccountController and comment InitializeSimpleMembership , because we using Custom Membership Provider instead of Simple Membership

9. Override Login Action of AccountController as follow :

10. Run the application ASP.NET MVC4 application Client,  you’ll have  the form authentication below:

 



11. Enter user credentials and click Log In, then you will have the execution workflow below:

Last Step – Configuring Custom Role Provider

1. create a class CustomRoleProvider  that inherits from  RoleProvider

2. Overrides GetRolesForUser method

 


3. Now open web.config file of your client asp.net web application and add a RoleManager section



4. Open HomeController and change Authorization as follow : 



5. Now test your sample. Only users who have approved login credentials and who belong to role Administrator can view Index page 



European ASP.NET MVC 5 Hosting - UK :: Tips Improving Your ASP.NET MVC Codebase

clock October 27, 2014 10:05 by author Scott

Some of you sometimes think why your application eat up until 1 GB-2GB memory on production server. After looking through the code, doing some profiling, maybe shaking your head a bit, you've figured out what the issue is and now you need to give some feedback.

In this tutorial, I will show some tips that you can follow to reduce your memory usage on production server and keep your ASP.NET MVC codebase working as you’d expect.

1. Understand the queries in your problem domain

The root cause of the support ticket I received was a simple case of fetching too much data from the database, causing obscene amounts of memory usage.

It's a common enough issue. You're building a simple blog, it has posts and it has media (images, videos, attachments). You put a Media array onto your Post domain object. Your Media domain object has all the image data stored in a byte array. Since you're using an ORM, there's a certain way you need to design your domain model to play nice; we've all experienced this.

public class BlogPost {
    public ICollection<BlogMedia> Media { get; set; }
}
public class BlogMedia {
    public byte[] Data { get; set; }
    public string Name { get; set; }
}

There's nothing absolutely wrong with this design. You've modeled your domain accurately. The problem is, when you issue a query through your favorite ORM, it eagerly loads all the data associated with your blog post:

public IList<BlogPost> GetNewestPosts(int take) {
    return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).ToList();
}

A seemingly innocuous line (unless you've been bitten), a sneaky monster is lying in wait with big consequences if you haven't disabled lazy loading or didn't tell your ORM to ignore that big Data property on blog media.

It's important to understand how your ORM queries and maps objects and make sure you only query what you need (for example using projection).

public IList<PostSummary> GetNewestPosts(int take) {
    return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).Select(p => new PostSummary() {
        Title = p.Title,
        Id = p.Id
    }).ToList();
}

This ensures we only grab the amount of data we really need for the task.

It's OK to have more than 5 methods on a repository; be as granular as you need to be for your UI.

2. Don't call your repositories from your views

Consider this line in an MVC view:

@foreach(var post in Model.RelatedPosts) {
    ...
}

It seems innocent enough. But if we take a look at what exactly that model property is hiding:

public class MyViewModel {

    public IList<BlogPost> RelatedPosts {
        get { return new BlogRepository().GetRelatedPosts(this.Tags); }
    }

}

Your "view model" has business logic in it on top of calling a data access method directly. Now you've introduced data access code somewhere it doesn't belong and hidden it inside a property. Move that into the controller so you can wrangle it in and populate the view model conciously.

This is a good opportunity to point out that implementing proper unit tests would uncover issues like this; because you definitely can't intercept calls to something like that and then you'd realize injecting a repository into a view model is probably not something you want to be doing.

3. Use partials and child actions to your advantage

If you need to perform business logic in a view, that should be a sign you need to revisit your view model and logic. I don't think it's advisable to do this in your MVC Razor view:

@{
    var blogController = new BlogController();
}

<ul>
@foreach(var tag in blogController.GetTagsForPost(p.Id)) {
    <li>@tag.Name</li>
}
</ul>

Putting business logic in the view is a no-no, but on top of that you're creating acontroller! Move that into your action method and use that view model you made for what it's intended for. You can also move that logic into a separate action method that only gets called inside views so you can cache it separately if needed.

//In the controller:

[ChildActionOnly]
[OutputCache(Duration=2000)]
public ActionResult TagsForPost(int postId) {
    return View();
}

//In the view:

@{Html.RenderAction("TagsForPost", new { postId = p.Id });}

Notice the ChildActionOnly attribute. From MSDN:

Any method that is marked with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.

This means people can't see your child action by manipulating the URL (if you're using the default route).

Partial views and child actions are useful tools in the MVC arsenal; use them to your advantage!

4. Cache what matters

Given the code smells above, what do you think will happen if you only cached your view model?

public ActionResult Index() {
    var homepageViewModel = HttpContext.Current.Cache["homepageModel"] as HomepageViewModel;

    if (homepageViewModel == null) {
        homepageViewModel = new HomepageViewModel();
        homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);

        HttpContext.Current.Cache.Add("homepageModel", homepageViewModel, ...);

    }

    return View(homepageViewModel);
}

Nothing! There will not be any performance gain because you're accessing the data layer through a controller variable in the view and through a property in the view model... caching the view model won't help anything.

Instead, consider caching the output of the MVC action instead:

[OutputCache(Duration=2000)]
public ActionResult Index() {
    var homepageViewModel = new HomepageViewModel();

    homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);

    return View(homepageViewModel);
}

Notice the handy OutputCache attribute. MVC supports ASP.NET Output Caching; use it to your advantage when it applies. If you are going to cache the model, your model needs to essentially be a POCO with automatic (and read-only) properties... not something that calls other repository methods.

Conclusion

I hope with tutorial above, it will help you to minimize your memory usage on the server.

 



European ASP.NET MVC 5 Hosting - UK :: Using Bootstrap 3 in ASP.NET MVC 5

clock October 21, 2014 10:00 by author Scott

In this article, we will describe about ASP.NET MVC 5 uses Bootstrap 3 as the CSS framework. You can check our last article about asp.net mvc 5 scaffolding.

Get Started with ASP.NET MVC 5

When you create a new ASP.NET MVC 5 Web Application in Visual Studio 2013 it is using Bootstrap 3 as its default CSS Framework. You get the pleasure of the responsive navigation and website along with all the typography and other bells and whistles you expect from Bootstrap 3.

Inside the ASP.NET MVC 5 Website Template you will find the bootstrap.css and bootstrap.min.css stylesheets as well as the bootstrap.js and bootstrap.min.js scripts. The _Layout.cshtml view and other views are marked up appropriately using the CSS selectors in Bootstrap 3.

ASP.NET MVC 5 Bootstrap

By default, the ASP.NET MVC Website Template uses a couple of bundles that use both Bootstrap 3 CSS as well as Modernizr. Check out the Layout.cshtml view to see the use of two of the bundles.

  @Styles.Render("~/Content/css")
 
@Scripts.Render("~/bundles/modernizr")

You will find these bundles configured in the BundleConfig.cs file in App_Start.

  bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
    
"~/Scripts/modernizr-*"
));

  bundles
.Add(new StyleBundle("~/Content/css").Include(
    
"~/Content/bootstrap.css"
,
    
"~/Content/site.css"
));

And, of course, the CSS selectors and markup in the new ASP.NET MVC 5 Views are based on Bootstrap 3.

That’s only brief tutorial about ASP.NET MVC 5. We will be back with new tutorial again.

 

 



European ASP.NET MVC 5 Hosting - UK :: ASP.NET MVC 5 Scaffolding

clock October 13, 2014 07:28 by author Scott

In this article, I will show you how to use Scaffolding With your ASP.net MVC 5 Application. I assume that you all know about scaffolding and I don’t need to explain it again. In our previous post, we have also explained about Scaffolding with the Repository Pattern in ASP.NET MVC 3.

In this article, we will be more focus in adding scaffolded item to ASP.net MVC 5.

1. Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.

2. Right click your Controllers folder and Add New Scaffolded Item is as below.

3. From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.

4. Add a controller. Please see the below screenshot

Then, please fill a name for your Data context as below, for example DataContext

5. You have done great job and this is the result

Testing the Result

Index Page

Create Page

Details Page

Edit Page

Delete Page

All above CRUD operations were generated according to our Model class Pet.

Pet.cs

Key points of the above code

  • [ScaffoldColumn(false)] means,the property which it declared will not use for scaffolding.In other words, that property will not be shown on the UI (i.e. Created property will not be shown).
  • Data validations of the form elements are happening ,according to the above model's Data Annotation values.
  • Let's explore it.

If you click the Create button, without entering anything.What will happen ?

What if you try to enter a wrong data type ?

 


Calender has been shown, if it's a DateTime property.

Great, right?



European ASP.NET MVC 5 Hosting - UK :: How to Fix Error Could not load file or assembly 'Microsoft.Web.Infrastructure'

clock September 24, 2014 07:39 by author Scott

We believe that some of you get this error when deploying your ASP.NET MVC 5 to shared hosting:

[FileNotFoundException: Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]

Previously, we have written blog about how to deploy your MVC to shared hosting environment. In this tutorial, we will be more focusing on above error message.

This is also one of a few component libraries that are needed for deploying an MVC application:

  • System.Web.Helpers.dll (required by the web.config)
  • System.Web.Mvc.dll
  • System.Web.Razor.dll
  • System.Web.WebPages.dll
  • System.Web.WebPages.Razor.dll
  • Microsoft.Web.Infrastructure.dll

The system libraries are installed with .NET 4, however, 'Microsoft.Web.Infrastructure.dll' is only installed when Visual Studio is installed on the machine.  Therefore, short of needing to install MVC and Visual Studio on a production environment, we need to deploy the libraries with out application - and we'd like to do so automatically.

There are a few ways to automatically deploy the 'Microsoft.Web.Infrastructure.dll' component library with your application.  The steps depend on which version of Visual Studio you are using.

1. Right-click on your project and select "Add Deployable Assemblies" and you'll see the following dialog:

2. When deploying for MVC, only choose the first option.  Never mind the second option even though it says "Razor syntax." The second option is for deploying the required libraries for projects officially known today as ASP.NET Web Pages. Once you click OK, you'll see a new folder appear in your project called _bin_deployableAssemblies with the required libraries.

For .NET, this is a special folder:

  • This is a secondary bin folder for framework dependencies.  If you right-click on any one of the .dll's shown in this folder, you'll see that the libraries are set to "Copy to Output Directory".  When the application is packaged/deployed, the libraries (and the folder) are also copied.  Again, the framework will also automatically check this folder for dependencies.
  • For .NET, any folder that begins with an underscore ("_") is considered private and non-accessible to the browser.  Therefore, you can rest knowing that the dependencies are secure.

Note that this process did not add any references to these libraries in your project.  They are simply here for the framework to run your MVC application.  If you do, in fact, need a type or class from one of these libraries, you are free to still add it as a reference as you normally would.

The above method is for Visual Studio 2010. How about in Visual Studio 2012? Then, please stay here, don’t exit from our blog. We almost finish our tutorial. Stay focus. :)

After Visual Studio 2010, the "Add Deployable Assemblies" option was removed from the project's options menu.  The system libraries are automatically copied to the Bin folder of your project. However, again, the 'Microsoft.Web.Infrastructure.dll' is only available on machines that have Visual Studio installed.  So how do you deploy this library with you application if you don't want to install Visual Studio on a production environment?  I'm glad you asked.  You'll need to use the Package Manager.

1. Run the following command in the package manager (if you're not familiar with Visual Studio, this can be reached by going to "Tools --> Library Package Manager --> Package Manager Console" in the top menu).

2. At the PM> prompt type

Install-Package Microsoft.Web.Infrastructure

3. You will see then see a message indicating that it has been installed and added to your project.

4. You'll also see that 'Microsoft.Web.Infrastructure.dll' has been added as a reference in your References folder.

5. Finally, now, when you deploy your application, 'Microsoft.Web.Infrastructure.dll' will be included in the Bin folder.

Conclusion

We hope with tutorial above, you can easily deploy your MVC application without any problem. If this article, please share it!! Please tell the world. :)



European ASP.NET MVC 6 Hosting - UK :: Try Newest ASP.NET MVC 6 Feature with HostForLIFE.eu!!

clock July 24, 2014 09:17 by author Scott

Good news here!! MVC 6 has been released by Microsoft. What interesting in ASP.NET MVC 6? ASP.NET MVC 6 which is called ASP.NET vNext, this includes so many new cloud optimized versions of MVC6, Web API3, Web Pages4, SignalR3 and Entity Framework7.

Below are some new features in ASP.NET MVC 6/ASP.NET vNext

  • ASP.NET vNext includes new cloud-optimized versions of MVC, Web API, Web Pages, SignalR, and Entity Framework
  • MVC, Web API and Web Pages have been merged into one framework, called MVC 6. This will follow common programming approach between all these three i.e. a single programming model for Web sites and services.
  • ASP.NET vNext apps are cloud ready by design. Services such as session state and caching will adjust their behavior depending on hosting environment either it is cloud or a traditional hosting environment. It uses dependency injection behind the scenes to provide your app with the correct implementation for these services for cloud or a traditional hosting environment. In this way, it will easy to move your app from on-premises to the cloud, since you need not to change your code.
  • .NET next version, .NET vNext is host agnostic. Hence you can host your ASP.NET vNEXT app in IIS, or self-host in a custom process
  • .NET vNext support true side-by-side deployment. If your app is using cloud-optimized subset of .NET vNext, you can deploy all of your dependencies including the .NET vNext (cloud optimized) by uploading bin to hosting environment. In this way you can update your app without affecting other applications on the same server
  • .NET vNext use the Roslyn compiler to compile code dynamically. Hence you will be able to edit a code file and can see the changes by refreshing the browser; without stopping or rebuilding the project
  • Dependency injection is built into the framework. Now, you can use your preferred IoC container to register dependencies.


European ASP.NET MVC Hosting - Germany :: The Difference Between ASP.NET MVC and Web API

clock July 16, 2014 08:05 by author Scott

In this article, I will explain the differences between ASP.NET MVC and ASP.NET Web API.

Overview of MVC

Model View Controller (MVC) divides an application into the three parts, Model, View and Controller. ASP.NET has many options for creating Web applications using the ASP.NET Web forms. MVC framework Combines the ASP.NET features such as Master pages, Membership based authentication. MVC exists in the "System.Web.MVC" assembly.

The components that are included by the MVC:

  • Models: Models are the objects used to retrieve and store the model state in the database.  Let's see an example. There is an "item" object that fetches the data from the database and performs an operation and then stores the updated data into the database. If an application only reads the dataset and sends it to the view then the application does not have any associated class and physical layer model
  • View: View components show the User Interface (UI) of the applications that is created by the data model. For example the view of the Items table shows the drop down list and textboxes that depend on the current state of the "item"  object.
  • Controllers: In MVC, controllers are also called the components. These components manage the user interaction and chooses a view for displaying the UI. The main work of the controller is that it manages the query string values and transfers these values to the models.

The Models retrieve the information and store the updated information in the database. Views are used for only displaying the information, and the controllers are used for managing and responding to the user inputs and their interaction.

Overview of the Web API

The ASP.NET Web API allows for displaying the data in various formats, such as XML and JSON. It is a framework that uses the HTTP services and makes it easy to provide the response to the client request. The response depends on the request of the clients. The web API builds the HTTP services and manages the request using the HTTP protocols. The Web API is an open source and it can be hosted in the application or on the IIS .The request may be GET, POST, DELETE or PUT. We can say that the Web API:

  • Is an HTTP service.
  • Is designed for reaching the broad range of clients.
  • Uses the HTTP application.

Difference between MVC and Web API

There are many differences between MVC and Web API, including:

  • We can use the MVC for developing  the Web application that replies as both data and views but the Web API is used for generating the HTTP services that replies only as data.
  • In the Web API the request performs tracing with the actions depending on the HTTP services but the MVC request performs tracing with the action name.
  • The Web API returns the data in various formats, such as JSON, XML and other format based on the accept header of the request. But the MVC returns the data in the JSON format by using JSONResult.
  • The Web API supports content negotiation, self hosting. All these are not supported by the MVC.
  • The Web API includes the various features of the MVC, such as routing, model binding but these features are different and are defined in the "System.Web.Http" assembly. And the MVC features are defined in the " System.Web.Mvc" assembly.
  • The Web API helps the creation of RESTful services over the .Net Framework but the MVC does not support.

When we combined the MVC with Web API:

When we do the self hosting on the application, in it we combine both the MVC controller and the API in a single project and it helps for managing the AJAX requests and returns the response in XML, JSON and other Formats.

We combined the MVC and Web API for enabling the authorization for an application. In it we create two filters, one for the Web API and another for MVC.



European ASP.NET MVC Hosting - Greece :: How to Remove IIS Header Bloat in ASP.NET MVC

clock June 26, 2014 09:30 by author Scott

Hi All, how do you do? In this post I will share little bit about how to remove IIS Header Bloat on IIS. This is default ASP.NET project’s response to a request for a page:

Cache-Control:private

Content-Encoding:gzip

Content-Length:3256

Content-Type:text/html; charset=utf-8

Date:Thu, 26 Jun 2014 09:07:59 GMT

Server:Microsoft-IIS/8.0

Vary:Accept-Encoding

X-AspNet-Version:4.0.30319

X-AspNetMvc-Version:4.0

X-Powered-By:ASP.NET

The first thing you need to do is remove X-AspNetMvc-Version header. How? Please just open your Global.asax.cs file to Application_Start, and add this code at the top

MvcHandler.DisableMvcResponseHeader = true;

Then, you can also eliminate the “Server” header by adding a handler to PreSendRequestHeaders event like this:

        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null &&
                app.Context != null)
            {
                app.Context.Response.Headers.Remove("Server");
            }
        }

Then, remove the “X-AspNet-Version" header by adding a config key to Web.Config. Here is the key to add (under <system.web>):

    <httpRuntime enableVersionHeader="false" />

The last is remove the X-Powered-By by adding another confing key to Web.Config (under<system.webserver>):

    <httpProtocol>

      <customHeaders>

        <remove name="X-Powered-By" />

      </customHeaders>

    </httpProtocol>

After doing all of this, we end up with a nice and clean response:

Cache-Control:private

Content-Encoding:gzip

Content-Length:3256

Content-Type:text/html; charset=utf-8
Date:Wed, 26 Jun 2014 09:17:09 GMTServer:Microsoft-IIS/8.0

Vary:Accept-Encoding



European ASP.NET MVC 5 Cloud Hosting - Austria :: Implementation ASP.NET MVC 5 Authentication Filters

clock June 5, 2014 09:01 by author Scott

ASP.NET MVC 5 offer many great new features. In today post, I will share one of the new ASP.NET MVC 5 feature which is called Authentication Filters and ASP.NET identity Management. ASP.NET MVC does not provide any built-in authentication filter(s). However it provides you with the framework, so you can easily create your own custom authentication filters.

 

In previous ASP.NET MVC 4, maybe you use AuthorizationFilters. New authentication filters run prior to authorization filters. It is also worth noting that these filters are the very first filters to run before any other filters get executed.

Why Use Authentication Filters?

Prior to authentication filters, developers used the Authorization filters to drive some of the authentication tasks for the current request. It was convenient because the Authorization filters were executed prior to any other action filters.  For example, before the request routes to action execution, we would use an Authorization filter to redirect an unauthenticated user to a login page. Another example would be to use the Authorization filter to set a new authentication principal, which is different from the application’s original principal in context.

Authentication related tasks can now be separated out to a new custom authentication filter and authorization related tasks can be performed using authorization filters. So it is basically about separating of concerns, while giving developers more flexibility to drive authentication using ASP.NET MVC infrastructure.

The Implementation ASP.NET MVC Authentication Filters

If you've done any development with ASP .NET MVC, you've more than likely used the Authorization attribute to enforce role-based security within your Web site. With MVC 5, you can now apply an Authentication filters to your controller to allow users to authenticate to your site from various third-party vendors or a custom authentication provider.

When applied to an entire controller class or a particular controller action, Authentication filters are applied prior to any Authorization filters. Let's see an Authentication filter in practice. Create a new C# ASP .NET Web Application, see Figure below.

Then, select ASP.NET project type.

Let's first look at how to implement a custom authentication filter that will simply redirect the user back to the login page if they're not authenticated. Create a new directory named CustomAttributes in your project. Next, create a new class named CustomAttribute that inherits from ActionFilterAttribute and IAuthenticationFilter:

public class BasicAuthAttribute: ActionFilterAttribute, IAuthenticationFilter

The IAuthenticationFilter interface defines two methods: OnAuthentication and OnAuthenhenticationChallenge. The OnAuthentication method is executed first and can be used to perform any needed authentication. The OnAuthenticationChallenge method is used to restrict access based upon the authenticated user's principal.

 For this simple example, I'll only be implementing the OnAuthenticationChallenge method and will leave the OnAuthenitcation method blank:

public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
    var user = filterContext.HttpContext.User;
    if (user == null || !user.Identity.IsAuthenticated)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

Here's the complete BasicAuthAttribute implementation:

using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace VSMMvc5AuthFilterDemo.CustomAttributes
{
    public class BasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            var user = filterContext.HttpContext.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}

You can now test out the BasicAuthAttribute by applying it to the HomeController class. Open up the HomeController class file, then add a using statement for your CustomAttributes namespace:

using VSMMvc5AuthFilterDemo.CustomAttributes;

Then apply the custom attribute to the HomeController class:

[BasicAuthAttribute]
public class HomeController : Controller

When you run the application, you should now be automatically redirected to the login page

In order to view the homepage, you must register a user account

Once your user is registered, you'll be automatically redirected to the homepage

As you can see, it isn't overly complex to implement a custom authentication filter within ASP.NET MVC 5.

Summary

The new IAuthenticationFilter provides a great ability to customize authentication within an ASP.NET MVC 5 application. This provides a clear separation between authentication and authorization filters. OnAuthentication and OnAuthenticationChallenge methods provide greater extensibility points to customize authentication within ASP.NET MVC framework. We also looked at a sample usage of CustomAuthentication attribute and how you can use to change the current principal and redirect un authenticated user to a login page.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in