Category: Microsoft

Multiple Ways to Build Routing in ASP.NET Core

url-routing

Routing in Microsoft MVC or WebAPI applications serves as a map to define the routes for all incoming requests. There are three basic components of routing in MVC , WebAPI applications Controller, Action method, and parameters.

Example:

https://www.betechnical.blog/account/login/24

In the provided link account is a controller, login is action method and 24 is parameter or query string.

Let’s review the different ways to build routing in ASP.NET CORE.

Creating Default Routes

By convention in your project’startup class, the default route can be defined.

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

   public void Configure(IApplicationBuilder app, 
                         IHostingEnvironment env, 
                         ILoggerFactory loggerFactory)
   {

      app.UseMvc(routes =>
      {

         routes.MapRoute(
                         name: "default",
                         template: "
                         {controller=Home}/{action=Index}/{id?}");

       });

    }
}

We need to be sure that essential configuration for MVC pattern of Controller + Action + ID route, exist in our project. Routing pattern can also be declared like: 

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

Extending Default Routes

On specific needs, Default Route can be extended by adding customized routes. By MapRoute() method, configurations can be added:

app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }
    );

    routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");
});

On the Home controller, Adding extra route allows access to About action with an/about the route. About page can be still accessed with conventional /home/about the route, as the default pattern route is still present.

Using Attributes

Using attributes in controller and actions, you can also configure routes.

[Route("[controller]")]
public class AnalyticsController: Controller
{

    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}

Now, controller actions can be accessed through the following routes:

  • /Analytics/Dashboard
  • /Analytics/Charts

Two tokens [controller] and [action] indicate that we have to refer to the controller and action name that has been declared. In this case, “Analytics” is the name of the controller, and “Charts” the name of the action, therefore it the name of the route.

Building RESTful Routes

We need to use the following route configuration, to declare a RESTful controller. 

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable Get()
    {
        return new string[] {"hello", "world!"};
    }

 
    // POST api/values
    [HttpPost]
    public void PostCreate([FromBody] string value)
    {

    }
}

 

Here, RESTful service is told to accept calls under the /api/values route. Now, we do not use the Route attribute for actions. Instead, we decorate it with HttpGet, HttpPost, HttpPut, HttpDelete attributes

Advertisements

LINQ Standard Query Operators

linq_480x400_acf_cropped

LINQ standard query operators are the methods which help you to write LINQ query. Most of these query methods operate on sequences or collection whose implement the IEnumerable interface or the IQueryable interface. These operators provide query capabilities including filtering, projection, aggregation, sorting and much more.

LINQ Standard Query Operators Sets

LINQ provides two sets of standard query operators, one set operates on objects of type IEnumerable and the other set operates on objects of type IQueryable. Also, these query methods (standard query operators) are static members of the Enumerable and Queryable static classes They are defined as extension methods of the type on which they operate. Hence, they are called either by using static method syntax or instance method syntax.

The query methods which are extended from IEnumerable, operate on in-memory collections. The query methods which are extended from IQueryable, operate on out-of-process memory collections and build an expression tree that represents the query to be performed.

Example for LINQ Query Method Where() Sets

In LINQ to Objects (in-memory collection), LINQ query methods would be used as an anonymous method, like Where():

public static IEnumerable Where(

this IEnumerable source, Func<TSource, bool> predicate)

While in LINQ to SQL (out-memory collection), mostly LINQ query methods would be used as the expression tree, like Where():

LINQ Query Method Execution

public static IQueryable Where(

this IQueryable source, Expression<Func<TSource, bool>> predicate)

The standard query operators are executed based on the value they return. The query methods that return a singleton value (like Average, Sum, Min, Max etc.) then execute immediately. The query methods that return a sequence or collection defer the query execution. The query methods can be chained together in one query.

Writing LINQ Query with the help of Standard Query Operators (LINQ Query Methods)

string sentence = "The quick brown fox jumps over the lazy dog";

 

// Split the string into individual words to create a collection.

string[] words = sentence.Split(' ');

 

// Using query expression syntax.

var query = from word in words

group word.ToUpper() by word.Length into gr

orderby gr.Key

select new { Length = gr.Key, Words = gr };

 

//You can also write above query by using method-based query syntax.

var query1 = words.

GroupBy(w => w.Length, w => w.ToUpper()).

Select(g => new { Length = g.Key, Words = g }).

OrderBy(o => o.Length);

 

//use either query or query1 variable to get result

foreach (var obj in query)

{

Console.WriteLine("\n Words of length {0}:", obj.Length);

foreach (string word in obj.Words)

Console.WriteLine(word);

}
  1. Words of length 3:

  2. THE

  3. FOX

  4. THE

  5. DOG

  6. Words of length 4:

  7. OVER

  8. LAZY

  9. Words of length 5:

  10. QUICK

  11. BROWN

  12. JUMPS

  13. */

ASP.NET MVC and ASP.NET Web API

confusion-clipart-4c9on8bzi

While developing your web application using MVC, many developers got confused when to use Web API, since MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In the previous article Web API and WCF the Most poppuler Frameworks of Microsoftt, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over others services. In this article, you will learn when to use Web API with MVC.

Asp.Net Web API VS Asp.Net MVC

  1. Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with the easy and simple way that returns only data, not view.

  2. Web API helps to build REST-ful services over the .NET Framework and it also supports content-negotiation(it’s about deciding the best response format data that could be acceptable by the client. it could be JSON, XML, ATOM or other formatted data), self-hosting which are not in MVC.

  3. Web API also takes care of returning data in particular format like JSON, XML or any other based upon the Accept header in the request and you don’t worry about that. MVC only return data in JSON format using JsonResult.

  4. In Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.

  5. Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these features exist within System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand-alone service layer.

  6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and be building a full blown HTTP service. Typically, this will be called Web API self-hosting.

  7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since both are different.

  8. Moreover, Web API is lightweight architecture and except the web application, it can also be used with smartphone apps.

How to Migrate Existing Web API Controllers by Using a Compatibility Shim

.NET and Microsoft decided to merge the MVC and Web API functionality, after the release of ASP.NET. If you are looking for the implementation of Web API with ASP.NET, Here is the way to accomplish:

Migrating Existing Web API Controllers by Compatibility Shim

You will have to alter one code to call AddWebApiConventions() if you use HttpResponseMessage in Web API controllers. It will help to know the proper serialize that response by wiring up the HttpResponseMessageOutputFormatter.

public void ConfigureServices(IServiceCollection services)
{
	// Add framework services.
	services.AddMvc().AddWebApiConventions(); //Add WebApi
}

}Depending upon your routing with Web API. You will need to register routes with Startup class.

In this way, you can migrate from your Web API code to ASP.NET Core. 

public void Configure(IApplicationBuilder app, 
                IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
	routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
    });
}

This sample controller helps you to use your ApiController within ASP.NET Core with compatibility Shim.

[Route("api/[controller]/[action]")]
public class ValuesApiController : ApiController
{
	[HttpGet]
	[ActionName("GetArray")]
	public IEnumerable GetArray()
	{
		//example returns a basic type that is automatically serialized as json - nothing special here
		return new string[] { "value2", "value3" };
	}

	[HttpGet]
	[ActionName("GetSomeJson")]
	public HttpResponseMessage GetSomeJson()
	{
		//example returns a HttpResponseMessage - the shim makes this possible
		var resp = new HttpResponseMessage()
		{
			Content = new StringContent("[{\"Name\":\"ABC\"},[{\"A\":\"1\"},{\"B\":\"2\"},{\"C\":\"3\"}]]")
		};

		resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
		return resp;
	}
}

 

Microsoft ASP.NET 4.5 Features

Microsoft’s ASP.NET, a standout amongst the best web application development framework ever. You can utilize ASP.NET to quickly create and convey very versatile, elite web applications in a managed situation. In this article, we will talk about the best 10 best highlights in ASP.NET 4.5 for developers:

Bundling and Minification Feature

With the help of Bundling and Minification Feature, you can bundle and minimize the script’s size and style the sheets in your application. It plays an important role in the performance of web application. You will notice the following lines in your Global.asax document, once create a new project in ASP.NET 4.5.

protected void Application_Start()

{

 //Some code

 BundleTable.Bundles.RegisterTemplateBundles();

}

Strongly Typed Data Controls

With ASP.NET 4.5, lets you strongly typed data controls. Simply, assign the item type property to a model, which is connected to data controls in .aspx pages. Following code illustrate the method:

          <%# Item.Name.ToString() %>

          

Value Providers 

 It provides numerous Value Providers like Cookie, Querystring, Control Value and Session to filter the data. Even, it lets you create custom value providers.

Support for OpenID in OAuth Logins

With the help of ASP.NET 4.5, external services can be used to login to your application, like you can register OAuth provider in the App_Start/AuthConfig.cs file. The data dictionary can also be used to pass additional data.

Support for improved paging in ASP.NET 4.5 GridView control

Paging support in ASP.NET 4.5 has been enhanced. GridView control has been enhanced. ASP.NET 4.5 GridView.AllowCustomPaging property gives awesome help to paging and dealing with a lot of information productively.

Enhanced support for asynchronous programming

ASP.NET 4.5 provides asynchronous programming support. It lets you read and write HTTP requests without OS threads and provides await and async keywords support.

Support for HTML5 form types

It also provides support to HTML5 form types like color, range, Date pickers, email, URL, number etc.

ASP.NET Web API

This is included in ASP.NET MVC 4 and ASP.NET Web Forms. ASP.NET Web API helps in building and consuming HTTP services easily.