ASP.NET MVC as a Service Framework overview

ASP.NET MVC  overviewIn the years since the first release of the .NET Framework, Microsoft has provided a variety of approaches for building service-oriented applications. Starting back in 2002 with the original release of .NET, a developer could fairly easily create an ASP.NET ASMX-based XML web service that allowed other .NET and non-.NET clients to call it. Those web services implemented various versions of SOAP, but were only available for use over HTTP.

In addition to web services, the 1.0 release of .NET provided support for Remoting. This allowed developers to write services that weren’t necessarily tied to the HTTP protocol. Similar to ASMX-based web services, .NET Remoting essentially provides object activation and session context for client-initiated method calls. The caller uses a proxy object to invoke methods, and the .NET runtime handles serialization and marshaling of data between the client’s proxy object and the server’s activated service object.


Table of contents[Show]


 

Towards the end of 2006, Microsoft released .NET 3.0, which included the Windows Communication Foundation (WCF). WCF not only replaced ASMX web services and .NET Remoting, but also took a giant step forward in the way of flexibility, configurability, extensibility, and support for more recent security and other SOAP standards. For example, with WCF, a developer can write a non-HTTP service that supports authentication with SAML tokens, and host it in a custom-built Windows service. These and other capabilities greatly broaden the scenarios under which .NET can be utilized to build a service-oriented application.

MORE ON WCF

If you’re interested in learning more about WCF, I recommend reading either Programming WCF Services by Juval Lowy [O’Reilly, 2007] or Essential Windows Communication Foundation by Steve Resnick, Richard Crane, and Chris Bowen [Addison-Wesley Professional, 2008]. Both of these books are appropriate for WCF novices and veterans alike, as they cover the spectrum from basic to advanced WCF topics.

If you need to set up communication between two applications, whether they are co-located or separated by thousands of miles, rest-assured WCF can do it. And if its out-of-the-box features don’t suffice, WCF’s tremendous extensibility model provides ample opportunity for plugging in just about anything you can think of.

And this is where we will take a bit of a left turn, off the evolutionary path of ever greater capability and flexibility, and towards something simpler and more targeted at a small set of specific scenarios.

 

In the Land of JavaScript and Mobile Devices

During much of the growth of the Internet over the past two-plus decades, web sites and pages have relied on server-side code for anything but basic HTML manipulation. But more recently, various AJAX-related tools and frameworks - including (but not limited to) JavaScript, jQuery, HTML5, and some tricks with CSS - have given rise to the need for services that are less about complex enterprise applications talking to each other and more about web pages needing to get and push small amounts of data. In these cases, communicating with a service over HTTP is pretty much a given, since the web sites themselves are HTTP applications. Further, security options available from within a browser are vastly simpler than those of an out-of-browser application, and thus support for all of the various security-related SOAP standards is not required of the service.

In addition to simpler protocol and security needs, web pages typically communicate with other applications and services using text-based messages rather than binary-formatted messages. As such, a service needs only to support XML or JSON serialization.

Beyond web applications, today’s smartphones and tablets have created a huge demand for services in support of small smart-client mobile applications. These services are very similar in nature to those that support AJAX-enabled web sites. For example, they typically communicate via HTTP; they send and receive small amounts of text-based data; and their security models tend to take a minimalist approach in order to provide a better user experience (i.e., they strive for less configuration and fewer headaches for users). Also, the implementation of these services encourages more reuse across the different mobile platforms.

In short, there is now a desire for a service framework that, out-of-the-box, provides exactly what is needed for these simple text-based HTTP services. While WCF can be used to create such services, it is definitely not configured that way by default. Unfortunately, the added flexibility and configurability of WCF make it all too easy to mess something up.

And this is where the ASP.NET MVC Framework comes into the picture.

 

Advantages of Using the MVC Framework

Once you know that, under certain scenarios, you aren’t interested in many of the capabilities of WCF, you can start thinking of a framework like ASP.NET MVC - with fewer service-oriented bells and whistles - as being advantageous. In this section, you’ll look in detail at a few of these.

 

Configuration

As is the case when building a web site, there isn’t much to configure to get an MVC-based service up and running. The concept of endpoints doesn’t exist, and neither do contracts. As you’ll see later, an MVC-based service is pretty loose in comparison to a WCF service. You pretty much just need a REST URL, a set of inbound arguments, and a response JSON or XML message.

 

REST by Default

Speaking of REST, building services with ASP.NET MVC and the Web API provides most of what you need to adhere to the constraints of the REST architecture. This is largely due to the URL routing feature provided by the MVC Framework. Unlike WCF, where a service is an address to a physical file (i.e., an address that maps directly to a service class or .svc file), service addresses with MVC are REST–style routes that map to controller methods. As such, the paths lend themselves very nicely to REST–style API specifications.

This concept of routing is critical to understanding how MVC can be used for building services, so let’s look at an example. In my blog you will learn how to develop a simple task-management service. You can imagine having a service method to fetch a single task. This method would take a task’s TaskId and return that task. Implemented in WCF, the method might look like this:

[ServiceContract]

public interface ITaskService

{
    [OperationContract]
    Task GetTask(long taskId);
}


public class TaskService : ITaskService

{

    private readonly IRepository _repository;

    public TaskService(IRepository repository)
    {
        _repository = repository;
    }


    public Task GetTask(long taskId)
    {
        return _repository.Get<Task>(taskId);
    }

}

 

With an appropriately configured .svc file and corresponding endpoint, you would have a URL that looks similar to this:
http://MyServer/TaskService.svc

The caller would then post a SOAP request with the SOAP action set to GetTask, passing in the TaskId argument. Of course, when building a .NET client, much of the underlying SOAP gunk is taken care of for you. But making SOAP calls from JavaScript can a bit more challenging, and - arguably - unnecessary.

This same example under ASP.NET MVC4 would involve creating a controller instead of a WCF service class. The method for fetching a Task object exists on the controller, but it is no longer defined by a contract, as it is in WCF. The controller might look like this:

public class TasksController : Controller

{

    private readonly IRepository _repository;

    public TasksController(IRepository repository)
    {
        _repository = repository;
    }


    public ActionResult Get(long taskId)
    {
        return Json(_repository.Get<Task>(taskId));
    }

}


With the TasksController, and an appropriately configured route, the URL used to fetch a single task would like this:

http://MyServer/Task/Get/123

Note that the method name “Get” appears in the URL. Let’s look briefly at an example built with the Web API:

public class TasksController : ApiController

{
    private readonly IRepository _repository;

    public TasksController(IRepository repository)
    {
        _repository = repository;
    }

    public Task Get(long taskId)
    {
        return repository.Get<Task>(taskId);
    }

}

One of the biggest changes is the base class used by the new controller, ApiController. This base class was built specifically for enabling RESTful services, and you simply return the object (or, objects in a collection) of the data being requested. Contrast this with the ActionResult shown in the preceding MVC4 example. Further, the URL itself will be different:

http://MyServer/Tasks/123

Note how the URL no longer needs to include the controller’s method name. This is because, with the Web API, HTTP verbs (e.g. GET, POST, PUT) are automatically mapped to corresponding controller methods. As you’ll see in the next my article, this helps you create an API that adheres more closely with the tenets of the REST architecture.

For now, the important thing to realize is that the entirety of this service call is contained in the URL itself; there is no SOAP message to go along with the address. And this is one of the key tenets of REST: resources are accessible via unique URIs.


A QUICK OVERVIEW OF REST

Created by Roy Fielding, one of the primary authors of the HTTP specification, REST is meant to take better advantage of standards and technologies within HTTP than SOAP does today. For example, rather than creating arbitrary SOAP methods, developers of REST APIs are encouraged to use only HTTP verbs:

  • GET
  • POST
  • PUT
  • DELETE

REST is also resource-centric; that is, RESTful APIs use HTTP verbs to act on or fetch information about resources. These would be the nouns in REST parlance (e.g., Tasks, Users, Customers, and Orders). Thus, you have verbs acting on nouns. Another way of saying this is that you perform actions against a resource.

Additionally, REST takes advantage of other aspects of HTTP systems, such as the following:

  • Caching
  • Security
  • Statelessness
  • Network layering (with various firewalls and gateways in between client and server)

My blog will cover REST principles sufficiently for you to build services using ASP.NET MVC. However, if you’re interested, you can find several good books that cover the full breadth of the REST architecture.

Before moving on, let’s address a point that some may be thinking about: you can indeed create REST services with WCF. Looking around the Internet, you can certainly find arguments on both sides of the MVC versus WCF debate (for building RESTful services). Since this is a blog on how to build services with MVC and the Web API, let’s skip that debate altogether.


 

Abstraction with Routes

Somewhat similar to service interfaces and their implementations in WCF, routes give the MVC service developer a layer of abstraction between what the callers see and the underlying implementation. In other words, you can map any URL to any controller method. When the API signature (i.e., the REST URL) isn’t hard-wired to a particular interface, class, or .svc file, you are free to update your implementation of that API method, as long as the URL specification for that method remains valid.

One classic example of using URLs to handle changing implementations is in the case of service versioning. By creating a new route with a “v2” (or similar) embedded in the URL, you can create an arbitrary mapping between an implementation and a versioning scheme or set of versions that doesn’t exist until sometime later. Thus, you can take a set of controllers (and their methods) and decide a year from now that they will be part of the v2 API.

 

Controller Activation Is, Well, Very Nice

Whether the subject is the older XML Web Services (a.k.a. ASMX services), WCF, or services with ASP.NET MVC, the concept of service activation is present. Essentially, since by-and-large all calls to a service are new requests, the ASP.NET or WCF runtime activates a new instance of the service class for each request. This is similar to object instantiation in OO-speak. Note that service activation is a little more involved than simply having the application code create a new object; this blog will touch on this topic in more depth in later my blog's articles.

ASP.NET MVC provides a simple mechanism for pre- and post-processing called action filters. These filters are essentially classes that contain a few methods allowing you to run some code before and after the controller methods are invoked. These action filters take the form of attributes, and they are either decorated on specific methods or configured globally for all methods.

It’s a bit tough to describe, but once you write and debug a few controllers - along with some action filters - you will start noticing how clean and easy Microsoft has made this arrangement. Nothing is hidden from you, making it simple to understand and step through an entire service call in the debugger.

 

Interoperability of JSON, XML, and REST

As mentioned previously, REST is based solely on existing HTTP standards, so it is extremely interoperable across all platforms capable of making HTTP requests. This not only includes computers, smartphones, and tablets, but it also gets into devices such as normal “old-fashioned” cell phones, DVRs, phone systems, ATM machines, refrigerators, alarm systems, browsers, digital watches - and the list goes on. As long as the device can make an HTTP request to a URL, it can “do” REST.

The same applies to JSON and straight XML data. Compared to SOAP, these technologies require very little in the way of proper formatting or an understanding of message specifications. Technically speaking, SOAP is an XML-based protocol. However, constructing a valid SOAP message (including envelope, header, and body) is quite a bit more complex than simply representing just your data with XML. The same can be said of parsing XML or JSON versus full-blown SOAP messages. And this complexity means that developers typically need SOAP libraries in order to construct and parse SOAP messages. The need for these libraries limits SOAP’s usability on small or specialty devices.

One of the main advantages of JSON, other than its drop-dead simplistic formatting, is that, for a given data package, it is much smaller in size than the same data represented as XML/SOAP. Again, this makes JSON very appealing for occasionally-connected or low-power devices, as well as those that are most often used over cellular networks.

This is not to say SOAP isn’t valuable or doesn’t have its place; quite the contrary, actually. The capabilities of the SOAP protocol go far beyond those of REST and JSON. Most of these capabilities are defined by the WS-* specifications (“WS” stands for “web services”). These specifications deal with more complex messaging needs such as message security, transactions, service discovery, metadata publishing, routing, trust relationships, and identity federation. None of these are possible with REST, as they require capabilities outside the scope of the HTTP protocol.

 

A Brief Introduction to the Web API

None of the aspects and advantages of using ASP.NET MVC discussed so far have had anything to do with the new MVC4 Web API. In truth, the MVC Framework itself - without the Web API - provides a simple yet powerful framework for building REST-based services.

That said, the new Web API available in MVC4 kicks things up yet another notch. It brings a whole slew of features that make it even easier and faster to build REST services. Let’s look at just a few of these new features:

  • Convention-based CRUD Actions : HTTP actions (e.g., GET and POST) are automatically mapped to controller methods (also known as controller actions) by their names. For example, on a controller called Products, a GET request such as /api/products will automatically invoke a method named “Get” on the controller. Further, the Web API automatically matches the number of arguments given in the URL to an appropriate controller method. Therefore, the URL /api/products/32 would automatically invoke the Get(long id) method. The same magic also applies to POST, PUT, and DELETE calls.
  • Built-in Content Negotiation : In MVC, controller methods that return JSON or XML have to be hard-coded to specifically return one of those content types. But with the Web API, the controller method need only return the raw data value, and this value will be automatically converted to JSON or XML, per the caller’s request. The caller simply uses an Accept or Content-Type HTTP header to specify the desired content type of the returned data, and the Web API ensures your return value gets formatted appropriately. Rather than returning an object of type JsonResult, you simply return your data object (e.g., Product or IEnumerable<Product>).
  • Automatic support for OData : By simply placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  • Self-hosting : With the Web API, you no longer need to use IIS to host HTTP services. Now your REST services can be hosted in a custom Windows service, console application, or any other type of host you need.

 

Summary

In this article, you learned how the ASP.NET MVC Framework provides a great platform for building REST-style Web APIs. In scenarios where much of the power and flexibility of WCF and SOAP aren’t needed, MVC can be a very simple and elegant alternative. These scenarios include applications that need to support only HTTP communication, as well as those that focus heavily on text-formatted messages.

You also learned about the various advantages of using ASP.NET MVC, including great support for REST, custom URL routes, and the interoperability of REST– and JSON–based services.

Finally, you were introduced to the all-new Web API and explored a few of the features it brings to the world of ASP.NET–based REST services.

Вас заинтересует / Intresting for you:

WordPress: using JavaScript Fr...
WordPress: using JavaScript Fr... 756 views dbstalker Mon, 31 Jan 2022, 15:59:37
What is RESTful? Full descript...
What is RESTful? Full descript... 2057 views Zero Cool Wed, 31 Oct 2018, 09:40:56
WordPress Themes: complete gui...
WordPress Themes: complete gui... 1232 views dbstalker Mon, 31 Jan 2022, 15:20:27
Mobile Apps Powered by WordPre...
Mobile Apps Powered by WordPre... 1241 views dbstalker Mon, 31 Jan 2022, 17:00:53
Comments (0)
There are no comments posted here yet
Leave your comments
Posting as Guest
×
Suggested Locations