A Great unification of Controllers: ASP.NET 5

This is another post on one of the cool features of ASP.NET 5. Microsoft introduced One ASP.NET concept with ASP.NET 4.5 which allows us to use MVC, Web API, Web forms in one project without any pain. But as we know that MVC and Web API follow the same coding constructs like controller, action but inherently they were different. There were some features like OutputCache (Refer one of my earlier post ) is available only with MVC not with Web API. Microsoft has redesigned ASP.NET MVC and Web API framework and made it truly one ASP.NET with vNext (ASP.NET 5). Now we can use the same controller to expose as an web-api endpoint and for returning the MVC views as well. As these are using the same framework now, all the features available with MVC can be seamlessly used with web api as well and vice versa.  Let’s have a pictorial look

Earlier versions of ASP.NET

All the MVC controllers are derived from Controller class under the name space System.Web.Mvc.

ControllersEarlierSimilarly Web API controllers derived from ApiController which belongs to the namespace System.Web.Http

APIController

With ASP.NET 5 –

NewControllerIn ASP.NET 5, Controller is part of namespace Microsoft.AspNet.Mvc and all the controller derives from this. These can be used either MVC controller or Web API controller or a combination of both as shown in above picture.

Note – With ASP.NET 5, Microsoft releases another version of MVC as ASP.NET MVC 6. In this post, I have referred MVC 6 many times based on the context.

Let’s explore it via example. We will create a simple asp.net mvc 6 application. We’ll start from asp.net 5 empty application.

  1. File -> New Project -> ASP.NET Web Application -> Type <Project name>.

  2. Select empty application from ASP.NET Preview templates and click Ok

  3. Now open project.json and add Microsoft.AspNet.Mvc in dependencies

  4. Create controllers, views and models folder in the solution as it is required by an MVC app

  5. Add a controller say HomeController

  6. Add a folder Home in Views and create an MVC View Index in it

  7. Now open startup.cs and add MVC in ConfigureServices method and use that in Configure method there and provide the default route.

I have added Index method at HomeController as

public ActionResult Index()
{
    ViewBag.Message = "Message set at server at " + System.DateTime.Now.ToLongTimeString();
    return View();
}

and the view looks like

@{
    // ViewBag.Title = "Home Page";
}
<h2>My MVC View</h2>
@ViewBag.Message

Let’s run our application-
FirstMVC

It is working as expected. We have just a created a normal ASP.NET MVC 6 application from an ASP.NET 5 empty solution.

 

 

Now we are going to use the same controller to add web api methods as well. We just need to add web api method as

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { DateTime.Now.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString() };
}

Now this method is available as api can be called as per requirement. Let’s use it as

<input type="button" value="Call Api" onclick="LoadData();" />&nbsp;
<div id="dvapidata"></div>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    function LoadData() {
        $.ajax({
            type: "Get",
            cache: false,
            url: "/Home/Get",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        });

    }
    function AjaxSucceeded(result) {
        $('#dvapidata').html(result);
    }
    function AjaxFailed(result) {
        alert('no success');
    }
</script>

Here I added a  method which initiates a jQuery Ajax call which calls the web api method that we added and put the result in div after request completes. To initiate the ajax call, we added a button on the page. Let’s run the application
MVCnWebAPI

Here we got the same MVC View and when we click on Call API button which call web api method via jQuery ajax. The response is encircled on the screenshot.

So we can see here that the same controller is used as MVC and Web API controller both. It is true one ASP.NET.

 

Some More Features

Let’s add some more flavors to this controller. To access the controller, we need to define the route templates that we defined in startup.cs. Let’s comment out that and just put app.usemvc() there as

startupAs we don’t have any route there so we need to define it at some other places. You might recall one more way of defining routes – attribute routing that got introduced with ASP.NET MVC 5. It is available here as well with some more cool enhancements. Let’s explore that

  • We can define the routes at controller and action as
    asp.net5riutesHere we can see that I have just put the route as /[controller] at class level, this is a generic route which take the name of the controller (Here Home),so even if the name of the controller changes we don’t need to change the route. Similarly, we provided the route definition on the action.
  • To define multiple or default routes, we can add more route to the controller as
    multiroyes
    Here we have given two routes to the controller one is already discussed above and other is a default route. So if user doesn’t give the controller name, it will take as Home. Similar we did for action as well. So now we can access this url as http://localhost:20199/home/index and http://localhost:20199/ both.
  • We can have different routes for different actions in the controller as
    DiffRoutes  In above screenshot, we can see that we gave two different routes on two action method of the same controller.

Note –  In ideal scenario, it is not good to use the same controller as MVC controller and Web API controller but they are now exactly same and in certain scenarios can be used. But the mail beauty of it that all the features available in MVC can be used seamlessly in MVC and Web API both

Hope you have enjoyed the post. Do share your feedback

Cheers
Brij

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s