European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting - HostForLIFE.eu :: Know Further About ASP.NET Core Endpoint Routing

clock January 29, 2020 08:49 by author Scott

Introduction

In this post I will explain the new Endpoint Routing feature that has been added to the ASP.NET Core middleware pipeline starting with version 2.2 and how it is evolving through to the upcoming version 3.0 that is at preview 3 at present time.

The motivation behind endpoint routing

Prior to endpoint routing the routing resolution for an ASP.NET Core application was done in the ASP.NET Core MVC middleware at the end of the HTTP request processing pipeline. This meant that route information, such as what controller action would be executed, was not available to middleware that processed the request before the MVC middleware in the middleware pipeline.

It is particularly useful to have this route information available for example in a CORS or authorization middleware to use the information as a factor in the authorization process.

Endpoint routing also allows us to decouple the route matching logic from the MVC middleware, moving it into its own middleware. It allows the MVC middleware to focus on its responsibility of dispatching the request to the particular controller action method that is resolved by the endpoint routing middleware.

The new Endpoint Routing middleware

Due to the above mentioned reasons, the endpoint routing feature was born to allow the route resolution to happen earlier in the pipeline in a separate endpoint routing middleware. This new middleware can be placed at any point in the pipeline after which other middleware in the pipeline can access the resolved route data.

The endpoint routing middleware API is evolving with the upcoming 3.0 version of the .NET Core framework. For that reason, the API that I will describe in the following sections may not be the final version of the feature. However the over all concept and understanding of how route resolution and dispatch work using endpoint routing should still apply.

In the following sections I will walk you through the current iterations of endpoint routing implementation from version 2.2 to version 3.0 preview 3, then I will note some changes that are coming based on the current ASP.NET Core source code.

The three core concepts involved in Endpoint Routing

There are three overall concepts that you need to understand to be able to understand how endpoint routing works.

These are the following:

  • Endpoint route resolution
  • Endpoint dispatch
  • Endpoint route mapping

Endpoint route resolution

The endpoint route resolution is the concept of looking at the incoming request and mapping the request to an endpoint using route mappings. An endpoint represents the controller action that the incoming request resolves to, along with other metadata attached to the route that matches the request.

The job of the route resolution middleware is to construct and Endpoint object using the route information from the route that it resolves based on the route mappings. The middleware then places that object into the http context where other middleware the come after the endpoint routing middleware in the pipeline can access the endpoint object and use the route information within.

Prior to endpoint routing, route resolution was done in the MVC middleware at the end of the middleware pipeline. The current 2.2 version of the framework adds a new endpoint route resolution middleware that can be placed at any point in the pipeline, but keeps the endpoint dispatch in the MVC middleware. This will change in the 3.0 version where the endpoint dispatch will happen in a separate endpoint dispatch middleware that will replace the MVC middleware.

Endpoint dispatch

Endpoint dispatch is the process of invoking the controller action method that corresponds to the endpoint that was resolved by the endpoint routing middleware.

The endpoint dispatch middleware is the last middleware in the pipeline that grabs the endpoint object from the http context and dispatches to particular controller action that the resolved endpoint specifies.

Currently in version 2.2 dispatching to the action method is done in the MVC middleware at the end of the pipeline.

In the version 3.0 preview 3, the MVC middleware is removed. Instead the endpoint dispatch happens at the end of the middleware pipeline by default. Because the MVC middleware is removed, the route map configuration that is usually passed to the MVC middleware, is instead passed to the endpoint route resolution middleware.

Based on the current source code, the upcoming 3.0 final release should have a new endpoint routing middleware that is placed at the end of the pipeline to make the endpoint dispatch explicit again. The route map configuration will be passed to this new middleware instead of the endpoint route resolution middleware as it is in version 3 preview 3.

Endpoint route mapping

When we define route middleware we can optionally pass in a lambda function that contains route mappings that override the default route mapping that ASP.NET Core MVC middleware extension method specifies.

Route mappings are used by the route resolution process to match the incoming request parameters to a route specified in the rout map.

With the new endpoint routing feature the ASP.NET Core team had to decide which middleware, the endpoint resolution or the endpoint dispatch middleware, should get the route mapping configuration lambda as a parameter.

In fact this is the part of the endpoint routing where the API is in flux. As I write this post, the route mapping is being moved from the route resolution middleware to the endpoint dispatcher middleware.

I will show you the route mapping API in version 3 preview 3 first, then show you the latest route mapping API in the ASP.NET Core source code. In the source code version, we will see that the route mapping is moved to the endpoint dispatcher middleware extension method.

Its important to note that the endpoint resolution happens during runtime request handling after the route mapping is setup during application startup configuration. Therefor the route resolution middleware has access to the route mappings during request handling regardless of which middleware the route map configuration is passed to. 

Accessing the resolved endpoint

Any Middleware after the endpoint route resolution middleware will be able to access the resolved endpoint through the HttpContext.

The following code snippet shows how this can be done in your own middleware:

//our custom middleware
app.Use((context, next) =>
{
    var endpointFeature = context.Features[typeof(Microsoft.AspNetCore.Http.Features.IEndpointFeature)]
                                           as Microsoft.AspNetCore.Http.Features.IEndpointFeature;

    Microsoft.AspNetCore.Http.Endpoint endpoint = endpointFeature?.Endpoint;

    //Note: endpoint will be null, if there was no
    //route match found for the request by the endpoint route resolver middleware
    if (endpoint != null)
    {
        var routePattern = (endpoint as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern
                                                                                   ?.RawText;

        Console.WriteLine("Name: " + endpoint.DisplayName);
        Console.WriteLine($"Route Pattern: {routePattern}");
        Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
    }
    return next();
});

As you can see I am accessing the resolved endpoint object through the IEndpointFeature or the Http Context. The framework provides wrapper methods to access the endpoint object without having to reach directly into the context as I have shown here.

Endpoint routing configuration

The middleware pipeline endpoint route resolver middleware, endpoint dispatcher middleware and endpoint route mapping lambda is setup in the Startup.Configure method of the Startup.cs file of ASP.NET Core project.

This configuration changed between 2.2 and 3.0 preview 3 versions and is still changing before the 3.0 release version. So in order to demonstrate the endpoint routing configuration I am going to declare the general form of the endpoint routing middleware configuration as pseudo code based on the three core concepts listed above:

//psuedocode that passes route map to endpoint resolver middleware
public void Configure(IApplicationBuilder app
                     , IHostingEnvironment env)
{
    //middleware configured before the UseEndpointRouteResolverMiddleware middleware
    //that does not have access to the endpoint object
    app.UseBeforeEndpointResolutionMiddleware();

    //middleware that inspects the incoming request, resolves a match to the route map
    //and stores the resolved endpoint object into the httpcontext
    app.UseEndpointRouteResolverMiddleware(routes =>
    {
        //This is the route mapping configuration passed to the endpoint resolver middleware
        routes.MapControllers();
    })

    //middleware after configured after the UseEndpointRouteResolverMiddleware middleware
    //that can access to the endpoint object
    app.UseAfterEndpointResolutionMiddleware();

    //The middleware at the end of the pipeline that dispatches the controler action method
    //will replace the current MVC middleware
    app.UseEndpointDispatcherMiddleware();
}

This version of our pseudo code shows the route mappings lambda passed as a parameter to the UseEndpointRouteResolverMiddleware endpoint route resolution middleware extension method.

An alternate version that matches what the current source code looks like, is shown below:

//psuedocode version 2 that passes route map to endpoint dispatch middleware
public void Configure(IApplicationBuilder app
                     , IHostingEnvironment env)
{
    app.UseBeforeEndpointResolutionMiddleware()

    //This is the endpoint route resolver middleware
    app.UseEndpointRouteResolverMiddleware();

    //This middleware can access the resolved endpoint object via HttpContext
    app.UseAfterEndpointResolutionMiddleware();

    //This is the endpoint dispatch middleware
    app.UseEndpointDispatcherMiddleware(routes =>
    {
        //This is the route mapping configuration passed to the endpoint dispatch middleware
        routes.MapControllers();
    });
}

In this version the route mapping configuration is passed as a parameter to the endpoint dispatch middleware extension method UseEndpointDispatcherMiddleware.

Either way the UseEndpointRouteResolverMiddleware() endpoint resolver middleware will have access to the route mappings at request handling time to do the route matching.

Once the route is matched by UseEndpointRouteResolverMiddleware an Endpoint object will be constructed with the route parameters and set to the httpcontext so that the middleware in the pipeline that follow, can access the Endpoint object and use it if needed.

In version 3 preview 3 version of this pseudo code, the route mapping is passed to UseEndpointRouteResolverMiddleware and there does not exist a UseEndpointDispatcherMiddleware at the end of the pipeline. This is because in this version the ASP.NET framework itself implicitly dispatches the resolved endpoint at the end of the request pipeline.

So the pseudo code representing version 3 preview 3 has the form below:

//pseudo code representing v3 preview 3 endpoint routing API
public void Configure(IApplicationBuilder app
                     , IHostingEnvironment env)
{
    app.UseBeforeEndpointResolutionMiddleware()

    //This is the endpoint route resolver middleware
    app.UseEndpointRouteResolverMiddleware(routes =>
    {
        //The route mapping configuration is passed to the endpoint resolution middleware
        routes.MapControllers();
    })

    //This middleware can access the resolved endpoint object via HttpContext
    app.UseAfterEndpointResolutionMiddleware()

    // The resolved endpoint is implicitly dispatched here at the end of the pipeline
    // and so there is no explicit call to a UseEndpointDispatcherMiddleware
}

This API looks to be changing with the 3.0 release version, as the current source code shows that the UseEndpointDispatcherMiddleware is added back in and it is the middleware that takes the route mappings as a parameter as illustrated by the second version of the pseudo code above.

Endpoint routing in version 2.2

If you create a Web API project using version 2.2 of the .NET Core SDK you will see the following code in the Startup.Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    //By default endpoint routing is not added
    //the MVC middleware dispatches the controller action
    //and the MVC middleware configures the default route mapping
    app.UseMvc();
}

The MVC middleware is configured at the end of the middleware pipeline using the UseMvc() extension method. This method internally sets the default MVC route mapping configuration at startup configuration time and dispatches the controller action during request handling.

By default the out of the box template in v2.2 just configures the MVC dispatcher middleware. As such the MVC middleware also handles the route resolution based on the route map configuration and the incoming request data.

However we can add Endpoint Routing using some additional configuration as shown below:

using Microsoft.AspNetCore.Internal;

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    //added endpoint routing that will resolve the endpoint object
    app.UseEndpointRouting();

    //middleware below will have access to the Endpoint

    app.UseHttpsRedirection();

    //the MVC middleware dispatches the controller action
    //and the MVC middleware configures the default route mapping
    app.UseMvc();
}

Here we have added the namespace Microsoft.AspNetCore.Internal. Including it, enables an additional IApplicationBuilder extension method UseEndpointRouting that is the endpoint resolution middleware that resolves the route and adds the Endpoint object to the httpcontext.

You can check out the source code for UseEndpointRouting extension method in version 2.2 at:

https://github.com/aspnet/AspNetCore/blob/v2.2.4/src/Http/Routing/src/Internal/EndpointRoutingApplicationBuilderExtensions.cs

In version 2.2 the MVC middleware at the end of the pipeline acts as the endpoint dispatcher middleware. It will dispatch the resolved endpoint to the proper controller action.

The endpoint resolution middleware uses the route mappings configured by the MVC middleware.

Once we have enabled endpoint routing we can actually inspect the resolved endpoint object if we add our own custom middleware show below:

using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseEndpointRouting();

    app.UseHttpsRedirection();

    //our custom middlware
    app.Use((context, next) =>
    {
        var endpointFeature = context.Features[typeof(IEndpointFeature)] as IEndpointFeature;
        var endpoint = endpointFeature?.Endpoint;

        //note: endpoint will be null, if there was no resolved route
        if (endpoint != null)
        {
            var routePattern = (endpoint as RouteEndpoint)?.RoutePattern
                                                          ?.RawText;

            Console.WriteLine("Name: " + endpoint.DisplayName);
            Console.WriteLine($"Route Pattern: {routePattern}");
            Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
        }
        return next();
    });

    app.UseMvc();
}

As you can see we can inspect and print out the endpoint object that the endpoint routing resolution middleware UseEndpointRouting has resolved. The endpoint object will be null, if the resolver was not able to match the request to a mapped route. We needed to pull in two additional namespaces to access the endpoint routing features.

Endpoint routing in Version 3 preview 3

In version 3 preview 3, endpoint routing will become a full fledged citizen of ASP.NET Core and we will finally have separation between the MVC controller action dispatcher and the route resolution middleware.

Here is the endpoint startup configuration in version 3 preview 3.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    app.UseRouting(routes =>
    {
        routes.MapControllers();
    });

    app.UseAuthorization();

    //No need to have a dispatcher middleware here.
    //The resolved endpoint is automatically dispatched to a controller action at the end
    //of the middleware pipeline
    //If an endpoint was not able to be resolved, a 404 not found is returned at the end
    //of the middleware pipeline
}

As you can see we have a app.UseRouting() method that configures the endpoint route resolution middleware. The method also takes a anonymous lambda function that configures the route mappings that the route resolver middleware will use to resolve the incoming request endpoint.

The routes.MapControllers() inside the mapping function configures the default MVC routes.

You will also notice that there is a app.UseAuthorization() after app.UseRouting() which configures the authorization middleware. This middleware will have access the httpcontext endpoint object set by the endpoint routing middleware.

Notice that we don’t have any MVC or endpoint dispatch middleware configured at the end of the method, after all other middleware configuration.

This is because the behavior of the version 3 preview 3 build is that the resolved endpoint will be implicitly dispatched to the controller action by the framework itself.

Similar to what we did for version 2.2 we can add the same custom middleware to inspect the resolved endpoint object.

using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    app.UseRouting(routes =>
    {
        routes.MapControllers();
    });

    app.UseAuthorization();

    //our custom middleware
    app.Use((context, next) =>
    {
        var endpointFeature = context.Features[typeof(IEndpointFeature)] as IEndpointFeature;
        var endpoint = endpointFeature?.Endpoint;

        //note: endpoint will be null, if there was no
        //route match found for the request by the endpoint route resolver middleware
        if (endpoint != null)
        {
            var routePattern = (endpoint as RouteEndpoint)?.RoutePattern
                                                          ?.RawText;

            Console.WriteLine("Name: " + endpoint.DisplayName);
            Console.WriteLine($"Route Pattern: {routePattern}");
            Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
        }
        return next();
    });

    //the endpoint is dispatched by default at the end of the middleware pipeline
}

Endpoint routing in upcoming ASP.NET Core version 3.0 source code repository

As we approach the version 3.0 release of the framework, it looks like the team is trying to make endpoint routing more explicit by adding back in the call to endpoint dispatcher middleware configuration. They are also moving back the route mapping configuration option to the dispatcher middleware configuration method.

We can see how this is changed yet again by peeking at the current source code.

Here is a snippet from the source code for the version 3.0 sample application music store at:

https://github.com/aspnet/AspNetCore/blob/master/src/MusicStore/samples/MusicStore/Startup.cs

public void Configure(IApplicationBuilder app)
{
    // Configure Session.
    app.UseSession();

    // Add static files to the request pipeline
    app.UseStaticFiles();

    // Add the endpoint routing matcher middleware to the request pipeline
    app.UseRouting();

    // Add cookie-based authentication to the request pipeline
    app.UseAuthentication();

    // Add the authorization middleware to the request pipeline
    app.UseAuthorization();

    // Add endpoints to the request pipeline
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "areaRoute",
            pattern: "{area:exists}/{controller}/{action}",
            defaults: new { action = "Index" });

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });

        endpoints.MapControllerRoute(
            name: "api",
            pattern: "{controller}/{id?}");
    });
}

As you can see that we have something similar to my pseudo code implementation that I detailed above.

Particularly, we still have the app.UseRouting() middleware setup from the version 3 preview 3, but now we also have an explicit app.UseEndpoints() endpoint dispatch method that more aptly named for what it does.

The UseEndpoints is a new IApplicationBuilder extension method that provides the endpoint dispatch implementation.

You can check out the source code for the UseEndpoints and UseRouting methods here:

https://github.com/aspnet/AspNetCore/blob/master/src/Http/Routing/src/Builder/EndpointRoutingApplicationBuilderExtensions.cs

Also note that the route mapping configuration lambda have been moved from the UseRouting middleware to the new UseEndpoints middleware.

The UseRouting endpoint route resolver will still have access to the mappings to resolve the endpoint at request handling time. Even though they are passed to the UseEndpoints middleware during startup configuration.

Adding Endpoint routing middleware to the DI container

To use endpoint routing, we also need to add the middleware to the DI container in the Startup.ConfigureServices method.

ConfigureServices in Version 2.2

For version 2.2 of the framework we need to explicitly add the call to services.AddRouting() method shown below to add the endpoint routing feature to the DI container:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting()

    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

ConfigureServices in Version 3 preview 3

For version 3 preview 3 build of the framework, endpoint routing already comes configured in the DI container under the covers in the AddMvc() extension method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddNewtonsoftJson();
}

Setting up Endpoint Authorization using endpoint routing and route mappings

When working with the version 3 preview 3 release we can attach authorization metadata to an endpoint. We do this using the route mappings configuration fluent API RequireAuthorization method.

The endpoint routing resolver will access this metadata when processing a request and add it to the Endpoint object that it sets on the httpcontext.

Any middleware in the pipeline after the route resolution middleware can access this authorization data by accessing the resolved Endpoint object.

In particular the authorization middleware can use this data to make authorization decisions.

Currently the route mapping configuration parameters are passed into the endpoint route resolver middleware, but as previously mentioned, in the future releases, the route mapping configuration will be passed into the endpoint dispatcher middleware.

Either way the attached authorization metadata will be available for the endpoint resolver middleware to use.

Below is an example of the version 3 preview 3 Startup.Configure method where I have added a new /secret route to the endpoint resolver middleware route map configuration lambda parameter:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    app.UseRouting(routes =>
    {
        routes.MapControllers();

        //Mapped route that gets attached authorization metadata using the RequireAuthorization extension method.
        //This metadata will be added to the resolved endpoint for this route by the endpoint resolver
        //The app.UseAuthorization() middleware later in the pipeline will get the resolved endpoint
        //for the /secret route and use the authorization metadata attached to the endpoint
        routes.MapGet("/secret", context =>
        {
            return context.Response.WriteAsync("secret");
        }).RequireAuthorization(new AuthorizeAttribute(){ Roles = "admin" });
    });

    app.UseAuthentication();

    //the Authorization middleware check the resolved endpoint object
    //to see if it requires authorization. If it does as in the case of
    //the "/secret" route, then it will authorize the route, if it the user is in the admin role
    app.UseAuthorization();

    //the framework implicitly dispatches the endpoint at the end of the pipeline.
}

You can see that I am using the RequireAuthorization method to add an AuthorizeAttribute attribute to the /secret route. This route will then only be authorized to be dispatched for a user in the admin role, by the authorization middleware, that comes before the endpoint dispatch occurs.

As I showed for version 3.3 preview 3 that we can add middleware to inspect the resolved endpoint object in httpcontext so can we here to inspect the AuthorizeAttribute added to the endpoint metadata:

using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    app.UseRouting(routes =>
    {
        routes.MapControllers();

        routes.MapGet("/secret", context =>
        {
            return context.Response.WriteAsync("secret");
        }).RequireAuthorization(new AuthorizeAttribute(){ Roles = "admin" });
    });

    app.UseAuthentication();

    //our custom middleware
    app.Use((context, next) =>
    {
        var endpointFeature = context.Features[typeof(IEndpointFeature)] as IEndpointFeature;
        var endpoint = endpointFeature?.Endpoint;

        //note: endpoint will be null, if there was no
        //route match found for the request by the endpoint route resolver middleware
        if (endpoint != null)
        {
            var routePattern = (endpoint as RouteEndpoint)?.RoutePattern
                                                          ?.RawText;

            Console.WriteLine("Name: " + endpoint.DisplayName);
            Console.WriteLine($"Route Pattern: {routePattern}");
            Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
        }
        return next();
    });

    app.UseAuthorization();

    //the framework implicitly dispatches the endpoint here.
}

This time I have added the custom middleware before the Authorization middleware and pulled in two additional namespaces.

Navigating to the /secret route and inspecting the metadata, you can see that it contains the Microsoft.AspNetCore.Authorization.AuthorizeAttribute type in addition to the Microsoft.AspNetCore.Routing.HttpMethodMetadata type.

References used for this article

The following articles contain source material that I used as a reference for this article:

https://devblogs.microsoft.com/aspnet/aspnet-core-3-preview-2/

Update for version 3 preview 4

Around the time I published this article, ASP.NET Core 3.0 preview 4 was released. It adds the changes that I described in the latest source code as can be seen in the code snippet from Startup.cs file below when creating a new webapi project:

//code from Startup.cs file in a webapi project template

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
            .AddNewtonsoftJson();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseHsts();

    app.UseHttpsRedirection();

    //add endpoint resolution middlware
    app.UseRouting();

    app.UseAuthorization();

    //add endpoint dispatch middleware
    app.UseEndpoints(endpoints =>
    {
        //route map configuration
        endpoints.MapControllers();

        //route map I added to show Authorization setup
        endpoints.MapGet("/secret", context =>
        {
            return context.Response.WriteAsync("secret");
        }).RequireAuthorization(new AuthorizeAttribute(){ Roles = "admin" }); 
    });
}

As you can see this version adds the explicit UseEndpoints middleware extension method at the end of the pipeline that adds the endpoint dispatch middleware. Also the route configuration parameter has been moved from the UseRouting method in preview 3 to the UseEndpoints in preview 4.

Conclusion

Endpoint routing allows ASP.NET Core applications to determine the endpoint that will be dispatched, early on in the middleware pipeline, so that later middleware can use that information to provide features not possible with the current pipeline configuration.

This makes the ASP.NET Core framework more flexible since it decouples the route matching and resolution functionality from the endpoint dispatching functionality, which until now was all bundled in with the MVC middleware.



European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Use AngularJS with MVC 6 Web API

clock February 10, 2017 08:46 by author Scott

This post will walk you through the step-by-step procedure on building a simple ASP.NET 5 application using AngularJS with Web API.

Before we dig further let’s talk about a quick overview of AngularJS and Web API in MVC 6.

Introducing AngularJS

AngularJS is a client-side MVC framework written in JavaScript. It runs in a web browser and greatly helps us (developers) to write modern, single-page, AJAX-style web applications. It is a general purpose framework, but it shines when used to write CRUD (Create Read Update Delete) type web applications.

Introducing Web API

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. In ASP.NET 5, Web API is now part of MVC 6. Read more here

Creating an ASP.NET 5 Project

To start, fire up Visual Studio 2015 and create a new ASP.NET 5 project by selecting File > New Project. In the dialog, under Templates > Visual C#, select ASP.NET Web Application as shown in the figure below: 

Name your project to whatever you like and then click OK. For this example I named the project as “AngularJS101”. Now after that you should be able to see the “New ASP.NET Project” dialog:

Now select ASP.NET 5 Preview Empty template from the dialog above. Then click OK to let Visual Studio generate the necessary files and templates needed for you. You should be able to see something like below:

Adding the Scripts folder

The next thing to do is to create a new folder called “Scripts”. This folder will contain all the JavaScript files needed in our application:

Getting the Required Packages

ASP.NET 5 now supports three main package managers: NuGet, NPM and Bower.

Package Manager

A package manager enables you to easily gather all resources that you need for building an application. In other words you can make use of package manager to automatically download all the resources and their dependencies instead of manually downloading project dependencies such as jQuery, Bootstrap and AngularJS in the web.

NuGet

NuGet manages .NET packages such as Entity Framework, ASP.NET MVC and so on. You typically specify the NuGet packages that your application requires within project.json file.

NPM

NPM is one of the newly supported package manager in ASP.NET 5. This package manager was originally created for managing packages for the open-source NodeJS framework. The package.json is the file that manages your project’s NPM packages.

Bower

Bower is another supported package manager in ASP.NET 5. It was created by Twitter that is designed to support front-end development. You can use Bower to manage client-side resources such as jQuery, AngularJS and Bootstrap.

For this example we need to use NPM to install the resources we need in our application such as Grunt and the Grunt plugins. To do this just right click in your Project (in this case AngularJS101) and select Add > New Item. In the dialog select NPM configuration file as shown in the figure below:

Click Add to generate the file for you. Now open package.json file and modify it by adding the following dependencies:

{
    "version": "1.0.0",
    "name": "AngularJS101",
    "private": true,
    "devDependencies": {
        "grunt": "0.4.5",
        "grunt-contrib-uglify": "0.9.1",
        "grunt-contrib-watch": "0.6.1"
    }
}

Notice that you get Intellisense support while you edit the file. A matching list of NPM package names and versions shows as you type.

In package.json file, from the code above, we have added three (3) dependencies named grunt, grunt-contrib-uglify and grunt-contrib-watch NPM packages that are required in our application.

Now save the package.json file and you should be able to see a new folder under Dependencies named NPM as shown in the following:

Right click on the NPM folder and select Restore Packages to download all the packages required. Note that this may take a bit to finish the download so just be patient and wait ;). After that the grunt, grunt-contrib-uglify and grunt-contrib-watch NPM packages should now be installed as shown in the following:

Configuring Grunt

Grunt is an open-source tool that enables you to build client-side resources for your project. For example, you can use Grunt to compile your LESS or Saas files into CSS. Adding to that, Grunt can also be used to minify CSS and JavaScript files.

In this example, we will use Grunt to combine and minify JavaScript files. We will configure Grunt so that it will take all the JavaScript files from the Scripts folder that we created earlier, combine and minify the files, and finally save the results to a file named app.js within the wwwroot folder.

Now right click on your project and select Add > New Item. Select Grunt Configuration file from the dialog as shown in the figure below:

Then click Add to generate the file and then modify the code within the Gruntfile.js file so it will look like this:

module.exports = function (grunt) { 
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.initConfig({
        uglify: {
            my_target: {
                files: { 'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js'] }
            }
        },

        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['uglify']
            }
        }
    });

    grunt.registerTask('default', ['uglify', 'watch']);
};

The code above contains three sections. The first one is used to load each of the Grunt plugins that we need from the NPM packages that we configured earlier. The initConfig() is responsible for configuring the plugins. The Uglify plugin is configured so that it combines and minifies all the files from the Scripts folder and generate the result in a file named app.js within wwwroot folder. The last section contains the definitions for your tasks. In this case we define a single ‘default’ task that runs ‘uglify’ and then watches for changes in our JavaScript file.

Now save the file and let’s run the Grunt file using Visual Studio Task Runner Explorer. To do this, go to View > Other Windows > Task Runner Explorer in Visual Studio main menu. In the Task Runner Explorer make sure to hit the refresh button to load the tasks for our application. You should see something like this:

Now right click on the default task and select Run. You should be able to see the following output:

Configuring ASP.NET MVC

There are two main files that we need to modify to enable MVC in our ASP.NET 5 application.

First, we need to modify the project.json file to in include MVC 6 under dependencies:

    "webroot": "wwwroot",
    "version": "1.0.0-*",
    "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
        "Microsoft.AspNet.Mvc": "6.0.0-beta3"
    },
    "frameworks": {
        "aspnet50": { },
        "aspnetcore50": { }
    },

Make sure to save the file to restore the packages required. The project.json file is used by the NuGet package manager to determine the packages required in your application. In this case we’ve added Microsoft.AspNet.Mvc.

Now the last thing is to modify the Startup.cs file to add the MVC framework in the application pipeline. Your Startup.cs file should now look like this:

using System; 
using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Http; 
using Microsoft.Framework.DependencyInjection;

namespace AngularJS101 
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services){
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app){
            app.UseMvc();
        }
    }
}

The ConfigureServices() method is used to register MVC with the ASP.NET 5 built-in Dependency Injection Framework (DI). The Configure() method is used to register MVC with OWIN.

Adding Models

The next step is to create a model that we can use to pass data from the server to the browser/client. Now create a folder named “Models” under the root of your project. Within the “Models” folder, create a class named “DOTAHero” and add the following code below:

using System;

namespace AngularJS101.Models 
{
    public class DOTAHero
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
    }
}

Create another class called “HeroManager” and add the following code below:

using System.Collections.Generic; 
using System.Linq;

namespace AngularJS101.Models 
{
    public class HeroManager
    {
        readonly List<DOTAHero> _heroes = new List<DOTAHero>() {
            new DOTAHero { ID = 1, Name = "Bristleback", Type="Strength"},
            new DOTAHero { ID = 2, Name ="Abbadon", Type="Strength"},
            new DOTAHero { ID = 3, Name ="Spectre", Type="Agility"},
            new DOTAHero { ID = 4, Name ="Juggernaut", Type="Agility"},
            new DOTAHero { ID = 5, Name ="Lion", Type="Intelligence"},
            new DOTAHero { ID = 6, Name ="Zues", Type="Intelligence"},
            new DOTAHero { ID = 7, Name ="Trent", Type="Strength"},
        };
        public IEnumerable<DOTAHero> GetAll { get { return _heroes; } }

        public List<DOTAHero> GetHeroesByType(string type) {
            return _heroes.Where(o => o.Type.ToLower().Equals(type.ToLower())).ToList();
        }

 public DOTAHero GetHeroByID(int Id) {
            return _heroes.Find(o => o.ID == Id);
        }
    }
}

The HeroManager class contains a readonly property that contains a list of heroes. For simplicity, the data is obviously static. In real scenario you may need to get the data in a storage medium such as database or any files that stores your data. It also contains a GetAll property that returns all the heroes and a GetHeroesByType() method that returns a list of heroes based on the hero type, and finally a GetHeroByID() method that returns a hero based on their ID.

Adding Web API Controller

For this particular example, we will be using Web API for passing data to the browser/client.

Unlike previous versions of ASP.NET, MVC and Web API controllers used the same controller base class. Since Web API is now part of MVC 6 then we can start creating Web API controllers because we already pulled the required NuGet packages for MVC 6 and configured MVC 6 in startup.cs.

Now add an “API” folder under the root of the project:

Then add a Web API controller by right-clicking the API folder and selecting Add > New Item. Select Web API Controller Class and name the controller as “HeroesController” as shown in the figure below:

Click Add to generate the file for you. Now modify your HeroesController class so it will look like this:

using System.Collections.Generic; 
using Microsoft.AspNet.Mvc; 
using AngularJS101.Models;

namespace AngularJS101.API.Controllers 
{
    [Route("api/[controller]")]
    public class HeroesController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<DOTAHero> Get()
        {
            HeroManager HM = new HeroManager();
            return HM.GetAll;
        }

        // GET api/values/7
        [HttpGet("{id}")]
        public DOTAHero Get(int id)
        {
            HeroManager HM = new HeroManager();
            return HM.GetHeroByID(id);
        }

    }
}

At this point we will only be focusing on GET methods to retrieve data. The first GET method returns all the heroes available by calling the GetAll property found in HeroManager class. The second GET method returns a specific hero data based on the ID.

You can test whether the actions are working by running your application in the browser and appending the /api/heroes in the URL. Here are the outputs for both GET actions:

Route: /api/heroes

Route: /api/heroes/7

Creating an AngularJS Application

Visual Studio 2015 includes templates for creating AngularJS modules, controllers, directives and factories. For this example we will be displaying the list of heroes using an AngularJS template.

Adding an AngularJS Module

To get started lets create an AngularJS module by right-clicking on the Scripts folder and selecting Add > New Item. Select AngularJS Module as shown in the figure below.

Click Add to generate the file and copy the following code for our AngularJS module:

(function () {
    'use strict';

    angular.module('heroesApp', [
        'heroesService'      
    ]);
})();

The code above defines a new AngularJS module named “heroesApp”. The heroesApp has a dependency on another AngularJS module named “heroesService” which we will create later in the next step.

Adding an AngularJS Controller

The next thing to do is to create a client-side AngularJS Controller. Create a new folder called “Controllers” under the Script folder as in the following:

 

Click Add and copy the following code below within your heroesController.js file:

(function () {
    'use strict';

    angular
        .module('heroesApp')
        .controller('heroesController', heroesController);

    heroesController.$inject = ['$scope','Heroes'];

    function heroesController($scope, Heroes) {
        $scope.Heroes = Heroes.query();
    }
})();

The code above depends on the Heroes service that supplies the list of heroes. The Heroes service is passed to the controller using dependency injection (DI). The $inject() method call enables DI to work. The Heroes service is passed as the second parameter to the heroesController() function.

Adding the Heroes Service

We will use an AngularJS Heroes service to interact with our data via Web API. Now add a new folder called “Services” within the Script folder. Right click on the Services folder and select Add > New Item. From the dialog select AngularJS Factory and name it as “heroesService.js” as in the following:

Now click Add and then replace the generated default code with the following:

(function () {
    'use strict';

    var heroesService = angular.module('heroesService', ['ngResource']);
    heroesService.factory('Heroes', ['$resource',
        function ($resource) {
            return $resource('/api/heroes', {}, {
                query: { method: 'GET', params: {}, isArray: true}
            });
        }
    ]);
})();

The code above basically returns a list of heroes from the Web API action. The $resource object performs an AJAX request using a RESTful pattern. The heroesService is associated with the /api/heroes route on the server. This means that when you perform a query against the service from your client-side code, the Web API HeroesController is invoked to return a list of heroes.

Adding an AngularJS Template

Let’s add an AngularJS template for displaying the list of heroes. To do this we will need an HTML page to render in the browser. In the wwwroot folder add a new HTML page and name it as “index” for simplicity. Your application structure should now look like this:

The wwwroot folder is a special folder in your application. The purpose is that the wwwroor folder should contain all contents of your website such as HTML files and images needed for your website.

You should not place any of your source code within the wwwroot folder. Instead source codes such as MVC controllers’ source, model classes and unminified JavaScript and LESS files should be placed outside of the wwwroot folder.

Now replace the content of index.html with the following:

<!DOCTYPE html>  
<html ng-app="heroesApp"> 
<head> 
    <meta charset="utf-8" />
    <title>DOTA 2 Heroes</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-resource.js"></script>
    <script src="app.js"></script>
</head> 
<body ng-cloak> 
    <div ng-controller="heroesController">
        <h1>DOTA Heroes</h1>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Type</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="hero in Heroes">
                    <td>{{hero.ID}}</td>
                    <td>{{hero.Name}}</td>
                    <td>{{hero.Type}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</body> 
</html> 

There are several things to point out from the markup above: 
The html element is embedded with the ng-app directive. This directive associates the heroesApp with the HTML file.

In the script section, you will notice that I use Google CDN for referencing AngularJS and related libraries. Besides being lazy, it’s my intent to use CDN for referencing standard libraries such as jQuery, AngularJS and Bootstrap to boost application performance. If you don’t want to use CDN then you can always install AngularJS packages using Bower.

The body element is embedded with the ng-cloak directive. This directive hides an AngularJS template until the data has been loaded in the page. 
The div element within the body block is embedded with the ng-controller directive. This directive associates the heroesController and renders the data within the div element.

Finally, the ng-repeat directive is added to the tr element of the table. This will create row for each data that retrieved from the server.

Output

Here’s the output below when running the page and navigating to index.html:

That’s it! It is more fun to play DOTA!

 



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.

 

 



FREE ASP.NET MVC 5 Cloud Hosting Belgium - HostForLIFE.eu :: About DataAnnotations, MVC and LINQ To Entities

clock May 6, 2014 07:18 by author Peter

In this blog I will be covering some useful features called DataAnnotations which one can use when using LINQ To Entities, together with ASP.NET MVC 5 Hosting. The outcomes of this blog are

  1. Understand and learn how you can create DataAnnotations on your LINQ To Entities generated model
  2. Understand how these annotations link with MVC Views which are then used to modify database data
  3. Understand how validators are then utilized automatically by ASP.NET following the annotations you create

The prerequisites of this blog are

  1. Have some understanding of LINQ To Entities
  2. Have some understanding of MVC and how you can create records using ASP.NET MVC
  3. Have SQL Server Express installed and have a database containing a Products table.

Whenever you create an ASP.NET MVC Template Project using Visual Studio an AccountModel inside the Models folder will be automatically generated. If you open this class you will note that there are some very useful properties which ASP.NET MVC uses to validate data inputted by the user. Let’s take a simple example.

public class LoginModel
 {
 [Required]
 [Display(Name = "User name")]
 public string UserName { get; set; }
[Required]
 [DataType(DataType.Password)]
 [Display(Name = "Password")]
 public string Password { get; set; }
[Display(Name = "Remember me?")]
 public bool RememberMe { get; set; }
 }

If you examine the above code you will note that on some specific fields there are what so called DataAnnotations. These DataAnnotations are
Display (line 4,9 and 12)
DataType (line 8)
Required (line 3 and 7)

What are these DataAnnotations and why are they used? These DataAnnotations basically give MVC some extra information on what you expect from the user when inputting data in an MVC View. For example, the Required DataAnnotation basically ensures that the specific field cannot be left empty. That would mean that a user would not be allowed to leave the field empty when inputting data. Thus, in the example shown above, the Username and Password fields are both required.The Display DataAnnotation, on the other hand, is used so that the label associated with the field, when displayed in an ASP.NET MVC View, will display the relevant Display information.

The DataType DataAnnotation will provide information on the DataType of that specific field. So for example, the Password field is in our case a Password field. This means that whenever you will be creating a View which accepts a LoginModel class, the Password field will be displayed as an HTML Input Type = password field.

The example which the ASP.NET MVC template project is very useful to let use understand how DataAnnotations can be used. However, what happens when you are using LINQ To Entities and you would have your classes already specified in your model. How can you use these very useful DataAnnotations and apply them to your LINQ To Entities model?

Basically my main aim is not to create DataAnnotations and apply them on a LINQ To Entities model which we have created in this blog. Thus, from now on I will assume that you have a LINQ To Entities class named Product which basically stores products information.

The first thing you will have to do is to create a partial class with the same name as your LINQ To Entities class. So ,in our example we will name our partial class Product. We would then create another class which will contain the MetaData containing all the fields in our LINQ To Entities Product model which we would like to apply DataAnnotations on. This code is shown underneath.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace MVCForBlog.Models
{
[MetadataType(typeof(ProductMetaData))]
 public partial class Product
 {
 }
public class ProductMetaData
 {
 [Required(ErrorMessage = "Product Name is required")]
 [Display(Name="Product Name")]
 [DataType( System.ComponentModel.DataAnnotations.DataType.Text)]
 public string ProductName { get; set; }
 [Required(ErrorMessage = "Product Description is required")]
 [DataType( System.ComponentModel.DataAnnotations.DataType.MultilineText)]
 [Display(Name = "Product Description")]
 public string ProductDescription { get; set; }
}
}

Before I go into the detail of what the above code does I will have to make some points very clear
To use DataAnnotations you should Add A Reference to the System.ComponentModel if this has not already been added
You should ensure that the partial class is in the SAME namespace as your LINQ To Entities model. THIS IS CRITICAL TO MAKE ANNOTATIONS WORK AS EXPECTED.
The fields you create in your class should have the SAME name as the field name specified in the LINQ To Entities model.

If you investigate the code listed you will note the following
From line 8 to line 11 we are creating a partial class with the same name as the class found in our LINQ To Entities model. We are then specifying that it will be using the MetaData created in a separate class named ProductMetaData

The ProductName field specified in line 17 has several data annotations applied. These include Required, which means that the user would not be able to leave the field empty, DisplayName which means that the field which will be displayed near the textbox will be shown as Product Name, and finally DataType which basically specifies what type of data the user should be inputting. In our case the ProductName is a string and thus we are specifying Text as the DataType.

The ProductDescription found in line 22, has the same DataAnnotations as in the previous field. However the DataType for this field is MultiLine text. Thus when this field will be displayed in an ASP.NET MVC View a TextArea will be shown.

Now let’s see how these annotations will affect the ASP.NET MVC View which will be used to create a new product to our database.

Create an ASP.NET MVC View which will create a new product to the database as shown in Figure 1. You will note that when you run your application and try to create a new product, the fields and GUI elements which will be created will reflect the DataAnnotations specified.



European Cloud ASP.NET MVC Hosting - Spain :: Pipeline in ASP.NET MVC

clock April 22, 2014 09:49 by author Scott

In this article, I will write simple tutorial about detail pipeline of ASP.NET MVC.

Routing

Routing is the first step in ASP.NET MVC pipeline. typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.

The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).

When ASP.NET MVC application starts at first time, it registers one or more patterns to the RouteTable to tell the routing system what to do with any requests that match these patterns. An application has only one RouteTable and this is setup in the Application_Start event of Global.asax of the application.

public class RouteConfig
   {
   public static void RegisterRoutes(RouteCollection routes)
   {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

   routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
   }
   }


protected void Application_Start()
{
   //Other code is removed for clarity
   RouteConfig.RegisterRoutes(RouteTable.Routes);
}

When the UrlRoutingModule finds a matching route within RouteCollection (RouteTable.Routes), it retrieves the IRouteHandler(System.Web.Mvc.IRouteHandler) instance(default is System.Web.MvcRouteHandler) for that route. From the route handler, the module gets an IHttpHandler(System.Web.IHttpHandler) instance(default is System.Web.MvcHandler).

public interface IrouteHandler
{
   IHttpHandler GetHttpHandler(RequestContext requestContext);
}

Controller Initialization

The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.

protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
   SecurityUtil.ProcessInApplicationTrust(delegate {
   IController controller;
   IControllerFactory factory;
   this.ProcessRequestInit(httpContext, out controller, out factory);
   try
   {
   controller.Execute(this.RequestContext);
   }
   finally
   {
   factory.ReleaseController(controller);
   }
   });
}

Action Execution

1. When the controller is initialized, the controller calls its own InvokeAction() method by passing the details of the chosen action method. This is handled by the IActionInvoker.

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)

2. After chosen of appropriate action method, model binders(default is System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data type conversion, data validation such as required or date format etc. and also take care of input values mapping to that action method parameters.

3. Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter. It is used to authenticate a user. Authentication filter process user credentials in the request and provide a corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and authorization to a user.

By default, Authenticate attribute is used to perform Authentication. You can easily create your own custom authentication filter by implementing IAuthenticationFilter.

4. Authorization filter allow you to perform authorization process for an authenticated user. For example, Role based authorization for users to access resources.

By default, Authorize attribute is used to perform authorization. You can also make your own custom authorization filter by implementing IAuthorizationFilter.

5. Action filters are executed before(OnActionExecuting) and after(OnActionExecuted) an action is executed. IActionFilter interface provides you two methods OnActionExecuting and OnActionExecuted methods which will be executed before and after an action gets executed respectively. You can also make your own custom ActionFilters filter by implementing IActionFilter.

6. When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.

Result Execution

1. Result filters are executed before(OnResultnExecuting) and after(OnResultExecuted) the ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and OnResultExecuted methods which will be executed before and after an ActionResult gets executed respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.

2. Action Result is prepared by performing operations on user inputs with the help of BAL or DAL. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult.

3. Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to the browser, falls into ViewResult category and other result type which returns only data either in text format, binary format or a JSON format, falls into NonViewResult category.

View Initialization and Rendering

1. ViewResult type i.e. view and partial view are represented by IView(System.Web.Mvc.IView) interface and rendered by the appropriate View Engine.

public interface Iview
{
  
void Render(ViewContext viewContext, TextWriter writer);
}

2. This process is handled by IViewEngine(System.Web.Mvc.IViewEngine) interface of the view engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your custom engine by using IViewEngine interface and can registered your custom view engine in to your Asp.Net MVC application as shown below:

protected void Application_Start()
{
  
//Remove All View Engine including Webform and Razor
   ViewEngines.Engines.Clear();
   //Register Your Custom View Engine
   ViewEngines.Engines.Add(new CustomViewEngine());
   //Other code is removed for clarity
}

3. Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be further extended very easily. In more complex scenario, it might render a form with client side validation with the help of JavaScript or jQuery.



Free ASP.NET 5 MVC Belgium Hosting - HostForLIFE.eu :: Implementing Validation Mechanism in ASP.NET MVC

clock April 16, 2014 07:17 by author Peter

In this article I will walk you through the steps of implementing validation in the ASP.NET 5 MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example
<input type=”button”
id=”btn”
onclick=”alert(‘hello world’)“
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {
$(‘#btn’).click(function (e) {
    alert(‘hello world’);
}
});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example. If our model is:

public
class
Person : Message
{
[GridColumn("Id", true)]
public
int Id { set; get; }
[Required]
[GridColumn("Name", false)]
[StringLength(10, ErrorMessage="Length cannot exceed to 10 character")]
public
string Name { set; get; }
}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this
@Html.EditorFor(model => model.Name)

This will generates an html as follows

<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

1. You can see that depending on the model it has automatically added the data-val-* properties in the html. You have to add a jquery.validation.unobtrusive.js in your project.

2. Then add the file path in the bundle like this:

bundles.Add(new
ScriptBundle(“~/bundles/jqueryval”).Include(
“~/Scripts/jquery.validate*”)); 

3. Then add the script reference in the page as within the script section like this.

@section scripts{
@Scripts.Render(“~/bundles/jqueryval”)

}

4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this.

$(‘#Save’).click(function (e) {
var $val = $(this).parents(‘form’);
if (!($val.valid()))
return
false;
else alert(‘form have no errors’);

}



Europe FREE ASP.NET MVC 5 Hosting - UK :: ASP.NET MVC 5 Hosting with HostForLIFE.eu

clock April 11, 2014 08:17 by author Scott

ASP.NET MVC 5.0 Overview

What's Asp.net MVC 5.0? Asp.net MVC 5.0 is is the latest version of the popular ASP.NET MVC technology that enables you to build dynamic websites using the Model-View-Controller technology, with an emphasis on a clean architecture, test-driven development and extensibility.

What're the new features from Asp.net mvc 5.0?

The ASP.NET MVC 5 Framework is the latest update to Microsoft’s popular ASP.NET web platform. It provides an extensible, high-quality programming model that allows you to build dynamic, data-driven websites, focusing on a cleaner architecture and test-driven development.

ASP.NET MVC 5 contains a number of improvements over previous versions, including some new features, improved user experiences; native support for JavaScript libraries to build multi-platform CSS and HTML5 enabled sites and better tooling support.

Below are some of new ASP.NET MVC 5 feature:

  • Scaffolding
  • ASP.NET Identity 
  • One ASP.NET 
  • Bootstrap 
  • Attribute Routing 
  • Filter Overrides

Best ASP.NET MVC 5.0 hosting service

If you read over the asp.net official web pages you should have found the mvc 5.0 is still developer preview release but not final product. If you're web developers you can simply get it installed on local and take all the advantages, however you might find it hard to find a real hosting service for it. Why? Because reliability is final purpose for production server, most hosting providers would not take the risk using some beta version softwares because they need to be responsible to all clients. Any potential security hole may destroy the entire server. But, you don’t need to worry, HostForLIFE.eu will provide ASP.NET MVC 5 hosting on our shared hosting environment. You can test drive this new feature with only €3.00/month.

More about Asp.net MVC 5.0 Hosting with HostForLIFE.eu

Asp.net MVC 5.0 will be a simple support by all leading asp.net hosting providers as long as it's officially released. There's no special requirement to get MVC 5.0 working but just a simple installation on server end. However it doesn't mean every service will be as good as advertised. For best performance and security purpose, you should always host your mvc application with a reputable service where the hosting servers are setup with powerful hardware and windows OS(windows server 2008 R2 is minimum requirement). The hosting service must be easy to use with friendly hosting control panel. The crucial point is you can always view your website online so 99% uptime must be offered.

HostForLIFE.eu offering super cheap hosting solutions and leading hosting features, you get unlimited disk space and unlimited bandwith in same hosting account. You also get dedicated application pools per site and free domain name opportunity. With standard websitepanel you can manage website files/database/email accounts and all other asp.net website configurations without professional skills. HostForLIFE.eu is by far the best choice for cheap and reliable asp.net mvc 5 hosting.



HostForLIFE.eu Proudly Announces Microsoft SQL Server 2014 Hosting

clock April 7, 2014 11:09 by author Peter
HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu a worldwide provider of hosting has announced the latest release of Microsoft's widely-used SQL relational database management system SQL Server Server 2014. You can take advantage of the powerful SQL Server Server 2014 technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages! In addition, SQL Server 2014 Hosting provides customers to build mission-critical applications and Big Data solutions using high-performance, in-memory technology across OLTP, data warehousing, business intelligence and analytics workloads without having to buy expensive add-ons or high-end appliances. 

SQL Server 2014 accelerates reliable, mission critical applications with a new in-memory OLTP engine that can deliver on average 10x, and up to 30x transactional performance gains. For Data Warehousing, the new updatable in-memory column store can query 100x faster than legacy solutions. The first new option is Microsoft SQL Server 2014 Hosting, which is available to customers from today. With the public release just last week of Microsoft’s latest version of their premier database product, HostForLIFE has been quick to respond with updated their shared server configurations.For more information about this new product, please visit http://hostforlife.eu/European-SQL-Server-2014-Hosting

About Us:
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.


European ASP.NET MVC 5 Hosting - Nederland :: How to Fix SimpleSecurity Error when Upgrading from MVC 4 to MVC 5

clock February 28, 2014 06:56 by author Scott

You will face this weird issue when you upgrade SimpleSecurity from MVC 4 to MVC 5 and this is an issue that you’ll see:

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed.

I did some research and found that others were having the same issue. Well it turns out I did not follow the instructions exactly.  Here is one note in the instructions I did not pay close attention to.

Note
: Microsoft-Web-Helpers has been replaced  with Microsoft.AspNet.WebHelpers. You should remove the old package first,  and then install the newer package.


I opened up the NuGet Package Manager and installed the package Microsoft.AspNet.WebHelpers and things started to work.  Note that when you create a new MVC 5 application and try to incorporate SimpleSecurity or SimpleMembership you will hit the same issue because Microsoft.AspNet.WebHelpers  is not installed by default.  It has to be present for SimpleMembership to run correctly.

I verified that all of the features in the reference application are working correctly after the upgrade.  Even the generation of the emails using Postal worked, which I was not sure of because of the upgrade of Razor as well.

One change I needed to make to the SimpleSecurity assembly was to remove the filters AuthorizeAttribute and BasicAuthorizeAttribute and put them in a separate assembly.  I did this because they are dependent upon MVC and Web API assemblies.  So now there is a version for MVC 4 and another for MVC 5. Please check https://simplesecurity.codeplex.com/SourceControl/latest for SimpleSecurity Project Source Code. Hope it helps



Press Release - Wordpress 3.8 Hosting with HostForLIFE.eu from Only €3.00/month

clock January 23, 2014 10:42 by author Scott

HostForLIFE.eu proudly launches the support of WordPress 3.8 on all their newest Windows Server environment. HostForLIFE.eu WordPress 3.8 Hosting plan starts from just as low as €3.00/month only.

WordPress is a flexible platform which helps to create your new websites with the CMS (content management system). There are lots of benefits in using the WordPress blogging platform like quick installation, self updating, open source platform, lots of plug-ins on the database and more options for website themes and the latest version is 3.8 with lots of awesome features.

WordPress 3.8 was released in December 2013, which introduces a brand new, completely updated admin design: with a fresh, uncluttered aesthetic that embraces clarity and simplicity; new typography (Open Sans) that’s optimized for both desktop and mobile viewing; and superior contrast that makes the whole dashboard better looking and easier to navigate.

HostForLIFE.eu is a popular online WordPress hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

Another wonderful feature of WordPress 3.8 is that it uses vector-based icons in the admin dashboard. This eliminates the need for pixel-based icons. With vector-based icons, the admin dashboard loads faster and the icons look sharper. No matter what device you use – whether it’s a smartphone, tablet, or a laptop computer, the icons actually scale to fit your screen.

WordPress 3.8 is a great platform to build your web presence with. HostForLIFE.eu can help customize any web software that company wishes to utilize. Further information and the full range of features WordPress 3.8 Hosting can be viewed here http://www.hostforlife.eu.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in