Tag Archives: WEB API

Serializing Entity Framework objects to JSON in ASP.NET Web API

Recently, I’ve been playing a lot with ASP.NET Web API, as it is really an exciting technology. It works exceptionally well with JSON.NET (Henrik Nielsen wrote a great post on how to return JSON from ASP.NET Web API using JSON.NET).

However, as it’s been the case in the past with i.e. WCF, I’ve run into a issue with serializing Entity Framework object to JSON when returning them from the ApiController. This is not, by any means, an issue in ASP.NET Web API, as the problem in this case lies in the EF lazy loading, which causes circular reference between the objects. This then throws a corresponding error – “A circular reference was detected while serializing an object of type (…)” if you are using JavaScriptSerializer, “Self referencing loop detected for type (…)” if you are using JSON.NET and so on.

I thought it might be useful to remind about possible solutions to this. There is an easy workaround.

More after the jump.

Our models & errors

For starters let’s take a look at our two simple models.

And the DbContext.

Finally, here is our ApiController.

If we try to return a simple Url from the ApiController, using the example above, we’d get the following error (note, the error comes from JSON.NET, but any other serializer would throw similar.

Solution – data projection

Data projection – in other words, passing to serializer only a selected set of values, in a form of an object different from Domain Model Object. DTO is a massive topic on its own, so I will not discuss it here. In case you are interested, there is a great article on that here. In short, let’s just say that many people consider using DTO these days a very poor approach, while others firmly believe that it is abolutely necessary to use DTO instead of trying to serialize your Domain Model Objects. Personally, I am a data projection advocate as to me it only makes sense to NOT expose domain models to the View.

Anyway, moving aside from the discussion, we could use data projection to an anonymous type in the LINQ query and serialize that. In other words, that would act kind of like a ViewModel.

This still wouldn’t compile as our old Get() method was returning a List, whereas in here we are dealing with IQueryable of Anonymous Type. Unfortunately there is no simple way to return IQueryable of Anonymous Type or IEnumerable of Anonymous Type from an ApiController method. So we’ll use a bit of hack and change the method signature to:

This is C# 4.0+ only, but we are talking ASP.NET Web API here, aren’t we? So the whole thing now looks like this:

Of course in this case we lose the type safety, but again, it produces the expected result.

Summary

If you run into problems with your EF objects, do not worry, there are ways to work around them. I’ve found this solution useful when experimenting with ASP.NET Web API, especially with much more complex entities that the ones used here as an example. If you don’t entirely agree, instead of returning anonymous object, you can also return a custom type, and effectively have a ViewModel.

you can also disable Lazy Loading in the constructor of the dbContext… I.E.
public DbContext(){
Configuration.LazyLoadingEnabled = false;
}
Then you won’t have to do it every time you need to use your DbContext.

If you wanted you could also use a viewmodel approach. While you are returning a view per se, you return a model designed around what you want exposed in the API.

public list Get()
{
var urls = db.Urls.Include(“Tags”).Select(i =>
new ViewModels.Url { i.Uid, i.UrlId, i.Address, i.Description, i.Tags});
return urls;
}

Token Based Authentication using ASP.NET Web API 2, Owin, and Identity

The demo application can be accessed on (http://ngAuthenticationWeb.azurewebsites.net). The back-end API can be accessed on (http://ngAuthenticationAPI.azurewebsites.net/) and both are hosted on Microsoft Azure, for learning purposes feel free to integrate and play with the back-end API with your front-end application. The API supports CORS and accepts HTTP calls from any origin. You can check the source code for this tutorial on Github.

AngularJS Authentication

 

Token Based Authentication

As I stated before we’ll use token based approach to implement authentication between the front-end application and the back-end API, as we all know the common and old way to implement authentication is the cookie-based approach were the cookie is sent with each request from the client to the server, and on the server it is used to identify the authenticated user.

With the evolution of front-end frameworks and the huge change on how we build web applications nowadays the preferred approach to authenticate users is to use signed token as this token sent to the server with each request, some of the benefits for using this approach are:

  • Scalability of Servers: The token sent to the server is self contained which holds all the user information needed for authentication, so adding more servers to your web farm is an easy task, there is no dependent on shared session stores.
  • Loosely Coupling: Your front-end application is not coupled with specific authentication mechanism, the token is generated from the server and your API is built in a way to understand this token and do the authentication.
  • Mobile Friendly: Cookies and browsers like each other, but storing cookies on native platforms (Android, iOS, Windows Phone) is not a trivial task, having standard way to authenticate users will simplify our life if we decided to consume the back-end API from native applications.

What we’ll build in this tutorial?

The front-end SPA will be built using HTML5, AngularJS, and Twitter Bootstrap. The back-end server will be built using ASP.NET Web API 2 on top of Owin middleware not directly on top of ASP.NET; the reason for doing so that we’ll configure the server to issue OAuth bearer token authentication using Owin middleware too, so setting up everything on the same pipeline is better approach. In addition to this we’ll use ASP.NET Identity system which is built on top of Owin middleware and we’ll use it to register new users and validate their credentials before generating the tokens.

As I mentioned before our back-end API should accept request coming from any origin, not only our front-end, so we’ll be enabling CORS (Cross Origin Resource Sharing) in Web API as well for the OAuth bearer token provider.

Use cases which will be covered in this application:

  • Allow users to signup (register) by providing username and password then store credentials in secure medium.
  • Prevent anonymous users from viewing secured data or secured pages (views).
  • Once the user is logged in successfully, the system should not ask for credentials or re-authentication for the next 24 hours 30 minutes because we are using refresh tokens.

So in this post we’ll cover step by step how to build the back-end API, and on the next post we’ll cover how we’ll build and integrate the SPA with the API.

Enough theories let’s get our hands dirty and start implementing the API!

Building the Back-End API

Step 1: Creating the Web API Project

In this tutorial I’m using Visual Studio 2013 and .Net framework 4.5, you can follow along using Visual Studio 2012 but you need to install Web Tools 2013.1 for VS 2012 by visiting this link.

Now create an empty solution and name it “AngularJSAuthentication” then add new ASP.NET Web application named “AngularJSAuthentication.API”, the selected template for project will be as the image below. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Web API Project Template

Step 2: Installing the needed NuGet Packages:

Now we need to install the NuGet packages which are needed to setup our Owin server and configure ASP.NET Web API to be hosted within an Owin server, so open NuGet Package Manger Console and type the below:

The  package “Microsoft.Owin.Host.SystemWeb” is used to enable our Owin server to run our API on IIS using ASP.NET request pipeline as eventually we’ll host this API on Microsoft Azure Websites which uses IIS.

Step 3: Add Owin “Startup” Class

Right click on your project then add new class named “Startup”. We’ll visit this class many times and modify it, for now it will contain the code below:

What we’ve implemented above is simple, this class will be fired once our server starts, notice the “assembly” attribute which states which class to fire on start-up. The “Configuration” method accepts parameter of type “IAppBuilder” this parameter will be supplied by the host at run-time. This “app” parameter is an interface which will be used to compose the application for our Owin server.

The “HttpConfiguration” object is used to configure API routes, so we’ll pass this object to method “Register” in “WebApiConfig” class.

Lastly, we’ll pass the “config” object to the extension method “UseWebApi” which will be responsible to wire up ASP.NET Web API to our Owin server pipeline.

Usually the class “WebApiConfig” exists with the templates we’ve selected, if it doesn’t exist then add it under the folder “App_Start”. Below is the code inside it:

Step 4: Delete Global.asax Class

No need to use this class and fire up the Application_Start event after we’ve configured our “Startup” class so feel free to delete it.

Step 5: Add the ASP.NET Identity System

After we’ve configured the Web API, it is time to add the needed NuGet packages to add support for registering and validating user credentials, so open package manager console and add the below NuGet packages:

The first package will add support for ASP.NET Identity Owin, and the second package will add support for using ASP.NET Identity with Entity Framework so we can save users to SQL Server database.

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “AuthContext” then paste the code snippet below:

As you can see this class inherits from “IdentityDbContext” class, you can think about this class as special version of the traditional “DbContext” Class, it will provide all of the Entity Framework code-first mapping and DbSet properties needed to manage the identity tables in SQL Server. You can read more about this class on Scott Allen Blog.

Now we want to add “UserModel” which contains the properties needed to be sent once we register a user, this model is POCO class with some data annotations attributes used for the sake of validating the registration payload request. So under “Models” folder add new class named “UserModel” and paste the code below:

Now we need to add new connection string named “AuthContext” in our Web.Config class, so open you web.config and add the below section:

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so add new class named “AuthRepository” and paste the code snippet below:

What we’ve implemented above is the following: we are depending on the “UserManager” that provides the domain logic for working with user information. The “UserManager” knows when to hash a password, how and when to validate a user, and how to manage claims. You can read more about ASP.NET Identity System.

Step 7: Add our “Account” Controller

Now it is the time to add our first Web API controller which will be used to register new users, so under file “Controllers” add Empty Web API 2 Controller named “AccountController” and paste the code below:

By looking at the “Register” method you will notice that we’ve configured the endpoint for this method to be “/api/account/register” so any user wants to register into our system must issue HTTP POST request to this URI and the pay load for this request will contain the JSON object as below:

Now you can run your application and issue HTTP POST request to your local URI: “http://localhost:port/api/account/register” or you can try the published API using this end point: http://ngauthenticationapi.azurewebsites.net/api/account/register if all went fine you will receive HTTP status code 200 and the database specified in connection string will be created automatically and the user will be inserted into table “dbo.AspNetUsers”.

Note: It is very important to send this POST request over HTTPS so the sensitive information get encrypted between the client and the server.

The “GetErrorResult” method is just a helper method which is used to validate the “UserModel” and return the correct HTTP status code if the input data is invalid.

Step 8: Add Secured Orders Controller

Now we want to add another controller to serve our Orders, we’ll assume that this controller will return orders only for Authenticated users, to keep things simple we’ll return static data. So add new controller named “OrdersController” under “Controllers” folder and paste the code below:

Notice how we added the “Authorize” attribute on the method “Get” so if you tried to issue HTTP GET request to the end point “http://localhost:port/api/orders” you will receive HTTP status code 401 unauthorized because the request you send till this moment doesn’t contain valid authorization header. You can check this using this end point: http://ngauthenticationapi.azurewebsites.net/api/orders

Step 9: Add support for OAuth Bearer Tokens Generation

Till this moment we didn’t configure our API to use OAuth authentication workflow, to do so open package manager console and install the following NuGet package:

After you install this package open file “Startup” again and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implemntation for this method as below:

Here we’ve created new instance from class “OAuthAuthorizationServerOptions” and set its option as the below:

  • The path for generating tokens will be as :”http://localhost:port/token”. We’ll see how we will issue HTTP POST request to generate token in the next steps.
  • We’ve specified the expiry for token to be 24 hours, so if the user tried to use the same token for authentication after 24 hours from the issue time, his request will be rejected and HTTP status code 401 is returned.
  • We’ve specified the implementation on how to validate the credentials for users asking for tokens in custom class named “SimpleAuthorizationServerProvider”.

Now we passed this options to the extension method “UseOAuthAuthorizationServer” so we’ll add the authentication middleware to the pipeline.

Step 10: Implement the “SimpleAuthorizationServerProvider” class

Add new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

As you notice this class inherits from class “OAuthAuthorizationServerProvider”, we’ve overridden two methods “ValidateClientAuthentication” and “GrantResourceOwnerCredentials”. The first method is responsible for validating the “Client”, in our case we have only one client so we’ll always return that its validated successfully.

The second method “GrantResourceOwnerCredentials” is responsible to validate the username and password sent to the authorization server’s token endpoint, so we’ll use the “AuthRepository” class we created earlier and call the method “FindUser” to check if the username and password are valid.

If the credentials are valid we’ll create “ClaimsIdentity” class and pass the authentication type to it, in our case “bearer token”, then we’ll add two claims (“sub”,”role”) and those will be included in the signed token. You can add different claims here but the token size will increase for sure.

Now generating the token happens behind the scenes when we call “context.Validated(identity)”.

To allow CORS on the token middleware provider we need to add the header “Access-Control-Allow-Origin” to Owin context, if you forget this, generating the token will fail when you try to call it from your browser. Not that this allows CORS for token middleware provider not for ASP.NET Web API which we’ll add on the next step.

Step 11: Allow CORS for ASP.NET Web API

First of all we need to install the following NuGet package manger, so open package manager console and type:

Now open class “Startup” again and add the highlighted line of code (line 8) to the method “Configuration” as the below:

Step 12: Testing the Back-end API

Assuming that you registered the username “Taiseer” with password “SuperPass” in the step below, we’ll use the same username to generate token, so to test this out open your favorite REST client application in order to issue HTTP requests to generate token for user “Taiseer”. For me I’ll be using PostMan.

Now we’ll issue a POST request to the endpoint http://ngauthenticationapi.azurewebsites.net/token the request will be as the image below:

OAuth Token Request

Notice that the content-type and payload type is “x-www-form-urlencoded” so the payload body will be on form (grant_type=password&username=”Taiseer”&password=”SuperPass”). If all is correct you’ll notice that we’ve received signed token on the response.

As well the “grant_type” Indicates the type of grant being presented in exchange for an access token, in our case it is password.

Now we want to use this token to request the secure data using the end point http://ngauthenticationapi.azurewebsites.net/api/orders so we’ll issue GET request to the end point and will pass the bearer token in the Authorization header, so for any secure end point we’ve to pass this bearer token along with each request to authenticate the user.

Note: that we are not transferring the username/password as the case of Basic authentication.

The GET request will be as the image below:

Token Get Secure Resource

If all is correct we’ll receive HTTP status 200 along with the secured data in the response body, if you try to change any character with signed token you directly receive HTTP status code 401 unauthorized.

Now our back-end API is ready to be consumed from any front end application or native mobile app.

taken from:http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Web API Content Negotiation

Inside Web API Content Negotiation

“Content negotiation” is often used to describe the process of inspecting the structure of an incoming HTTP request to figure out the formats in which the client wishes to receive responses. Technically, though, content negotiation is the process in which client and server determine the best possible representation format to use in their interactions. Inspecting the request typically means looking into a couple of HTTP headers such as Accept and Content-Type. Content-Type, in particular, is used on the server for processing POST and PUT requests and on the client for choosing the formatter for HTTP responses. Content-Type is not used for GET requests.

The internal machinery of content negotiation, however, is much more sophisticated. The aforementioned scenario is the most typical—because of default conventions and implementations—but it isn’t the only one possible.

The component that governs the negotiation process in Web API is the class called DefaultContentNegotiator. It implements a public interface (IContentNegotiator), so you can replace it entirely if needed. Internally, the default negotiator applies several distinct criteria in order to figure out the ideal format for the response.

The negotiator works with a list of registered media type formatters—the components that actually turn objects into a specific format. The negotiator goes through the list of formatters and stops at the first match. A formatter has a couple of ways to let the negotiator know it can serialize the response for the current request.

The first check occurs on the content of the MediaTypeMappings collection, which is empty by default in all predefined media type formatters. A media type mapping indicates a condition that, if verified, entitles the formatter to serialize the response for the ongoing request. There are a few predefined media type mappings. One looks at a particular parameter in the query string. For example, you can enable XML serialization by simply requiring that an xml=true expression is added to the query string used to invoke Web API. For this to happen, you need to have the following code in the constructor of  your custom XML media type formatter:

MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "text/xml"));

In a similar way, you can have callers express their preferences by adding an extension to the URL or by adding a custom HTTP header:

MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "text/xml"));
MediaTypeMappings.Add(new RequestHeaderMapping("xml", "true",
  StringComparison.InvariantCultureIgnoreCase, false,"text/xml"));

For URL path extension, it means the following URL will map to the XML formatter:

http://server/api/news.xml

Note that for URL path extensions to work you need to have an ad hoc route such as:

config.Routes.MapHttpRoute(
  name: "Url extension",
  routeTemplate: "api/{controller}/{action}.{ext}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

For custom HTTP headers, the constructor of the RequestHeaderMapping class accepts the name of the header, its expected value and a couple of extra parameters. One optional parameter indicates the desired string comparison mode, and the other is a Boolean that indicates if the comparison is on the entire string. If the negotiator can’t find a match on the formatter using the media type mapping information, it looks at standard HTTP headers such as Accept and Content-Type. If no match is found, it again goes through the list of registered formatters and checks whether the return type of the request can be serialized by one of the formatters.

To add a custom formatter, insert something like the following code in the startup of the application (for example, in the Application_Start method):

config.Formatters.Add(xmlIndex, new NewsXmlFormatter());

Customizing the Negotiation Process

Most of the time, media type mappings let you easily fulfill any special requirements for serialization. However, you can always replace the default content negotiator by writing a derived class and overriding the MatchRequestMediaType method:

protected override MediaTypeFormatterMatch MatchRequestMediaType(
  HttpRequestMessage request, MediaTypeFormatter formatter)
{
  ...
}

You can create a completely custom content negotiator with a new class that implements the IContentNegotiator interface. Once you have a handmade negotiator, you register it with the Web API runtime:

GlobalConfiguration.Configuration.Services.Replace(
  typeof(IContentNegotiator),
  new YourOwnNegotiator());

The preceding code usually goes in global.asax or in one of those handy config handlers that Visual Studio creates for you in the ASP.NET MVC Web API project template.

Controlling Content Formatting from the Client

The most common scenario for content negotiation in Web API is when the Accept header is used. This approach makes content formatting completely transparent to your Web API code. The caller sets the Accept header appropriately (for example, to text/xml) and the Web API infrastructure handles it accordingly. The following code shows how to set the Accept header in a jQuery call to a Web API endpoint to get back some XML:

$.ajax({
  url: "/api/news/all",
  type: "GET",
  headers: { Accept: "text/xml; charset=utf-8" }
});

In C# code, you set the Accept header like this:

var client = new HttpClient();
client.Headers.Add("Accept", "text/xml; charset=utf-8");

Any HTTP API in any programming environment lets you set HTTP headers. And if you foresee that you can have callers where this might be an issue, a best practice is to also add a media type mapping so the URL contains all the required information about content formatting.

Bear in mind that the response strictly depends on the structure of the HTTP request. Try requesting a Web API URL from the address bar of Internet Explorer 10 and Chrome. Don’t be surprised to see you get JSON in one case and XML in the other. The default Accept headers might be different in various browsers. In general, if the API will be publicly used by third parties, you should have a URL-based mechanism to select the output format.

Scenarios for Using Web API

Architecturally speaking, Web API is a big step forward. It’s becoming even more important with the recent Open Web Interface for .NET (OWIN) NuGet package (Microsoft.AspNet.Web­­Api.Owin) and Project Katana, which facilitate hosting the API in external apps through a standard set of interfaces. If you’re building solutions other than ASP.NET MVC applications, using Web API is a no-brainer. But what’s the point of using Web API within a Web solution based on ASP.NET MVC?

With plain ASP.NET MVC, you can easily build an HTTP façade without learning new things. You can negotiate content fairly easily with just a bit of code in some controller base class or in any method that needs it (or by creating a negotiated ActionResult). It’s as easy as having an extra parameter in the action method signature, checking it and then serializing the response to XML or JSON accordingly. This solution is practical as long as you limit yourself to using XML or JSON. But if you have more formats to take into account, you’ll probably want to use Web API.

As previously mentioned, Web API can be hosted outside of IIS—for example, in a Windows service. Clearly, if the API lives within an ASP.NET MVC application, you’re bound to IIS. The type of hosting therefore depends on the goals of the API layer you’re creating. If it’s meant to be consumed only by the surrounding ASP.NET MVC site, then you probably don’t need Web API. If your created API layer is really a “service” for exposing the API of some business context, then Web API used within ASP.NET MVC makes good sense.

set a Web API REST service to always return XML not JSON

//Version 1, working as of 2012-05-17…

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();

//Needed to add the following line in order to return XML or else it always returns JSON.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseDataContractSerializer = true;
}

//Version 2, candidate as of 2012-05-17…

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();

//Clear all the formatters from the config.Formatters collection and just add back the XmlMediaTypeFormatter.
//That will ensure you only have one available formatter
//http://forums.asp.net/t/1804419.aspx/2/10?how+to+set+a+Web+API+REST+service+to+always+return+XML+not+JSON
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());
}

ASP.NET Web API 2.1 RC is out

The ASP.NET team kept it’s frantic work pace and already before Christmas dropped onNuget a 2.1 RC of Web API (as well as new MVC and Web Pages).

While in the open source mode of operation (public commits, nightly builds) this is that big of a news, it is still a very nice piece of news. Let’s look at what’s new.

Overview of ASP.NET Web API 2.1 RC

The official release notes are available here. Most of the features you have already seen – as on this blog we try to cover both existing and the upcoming bits of the Web API framework.

You can grab the release from Nuget:

Shell
1
Install-Package Microsoft.AspNet.WebApi -Pre

 

Glboal error handling

Arguably the biggest feature of this drop – something that has been very heavily discussed i nthe advisors meetings and in the discussion list.

The full feature specification is available here.

Now, in short, you get a single point of error handling for your Web API – something that didn’t exist before, and trying to handle all errors required you to catch in many places (or resort toGlobal.asax).

Up to this point you could use ExceptionFilters for more or less widely-scoped error handling; but they wouldn’t catch exceptions from message handlers, media type formatters or routing.

The simplest example is absolutely trivial:

C#
1
2
3
4
5
6
7
public class TraceExceptionLogger : ExceptionLogger
{
    public override void LogCore(ExceptionLoggerContext context)
    {
        Trace.TraceError(context.ExceptionContext.Exception.ToString());
    }
}

 

BSON formatter

Web API now supports application/bson out of the box. We have written a BSON formatter on this blog back in the summer of 2012 and it’s also a part of WebApiContrib, but it’s nice to have it in the core, especially as it doesn’t bring in any external dependencies (it relies on JSON.NET).

It has also been hardedned a bit, so that’s another plus.

Async filters

I have just recently blogged about async filters for Web API. As mentioned there, the vNext will have it in the box, and as a result, you can enjoy this feature in Web API 2.1 RC.

Ignore routes

HttpRoutesCollection will now support IgnoreRoute mechanism, allowing you to easily exclude parts of your routing hierarchy from being matched.

Attribute routing enhancements

Attribute routing now provides new extensibility hooks. They are described in detail here (bottom of the page) and allow you to provide instructions on custom route resolution (IDirectRouteProvider). This is extremely useful when trying to do something like versioning or localization.

Fixes, fixes, fixes

Plenty of bug fixes too. Among the more interesting ones:

Web API 2’s Attribute Routing: Looking Deeper

While most of us are used to creating routes using the Web API configuration, attributed routes are different. Before attributed routing, when you would look at the route data (e.g. request.GetRouteData()) you would get a route with a name that tied to the configured name. This was really useful for the way to use UrlHelper to build your URLs.

In fact, you can get this behavior by supplying names to the individual routes in your attributed routing:

1
2
3
4
5
6
7
8
9
10
11
12
13
public FooController : ApiController
{
  [Route("api/foos", Name = "Foo")]
  public object Get()
  {
    // ...
  }
}
...
var helper = new UrlHelper(Request);
var url = helper.Link("Foo");

But if you’re traversing the route collection in any way (e.g. in a ControllerSelector) it is important to understand where these routes actually are. When you use attribute routing, all the route attributes get added to a common route without a name. This is a special route that is an instance of an internal class called RouteCollectionRoute (Source Link). This route has a collection of sub-routes that you can query for that includes *all* the attribute routes. But if you just want the selected route for your call, you can simple ask for it using the RouteData.Values:

1
2
3
var routeData = request.GetRouteData();
var subroutes = (IEnumerable<IHttpRouteData>)routeData.Values["MS_SubRoutes"];
var route = subroutes.First().Route;

The real problem for some is that there is no longer controller name in the route data. This makes sense of course because there is no specific controller that a route points to as attributed routes are related to methods, not controllers. Being aware of these internals may help you solve issues when you use or move to using attributed routes.

Top 5 New Features in ASP.NET Web API 2

ASP.NET Web API 2 has been released with a number of new exciting features.

1. Attribute Routing

Along with convention-based routing, Web API 2 now supports attribute routing as well.

In case of convention-based routing, we can define multiple route templates. When a request comes, it will be matched against already defined route templates, and forwarded to specific controller action according to matched template.

You can see the following default route template in routing table for Web API:

Config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{Controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);

This routing approach has benefits that all routing templates are defined at one common location but for certain URI patterns, it really becomes difficult to support (like nested routing on same controller).

With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as well. Following shows an example of a URI pattern with attribute routing. URI Pattern –> books/1/authors

[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ..... }

2. CORS – Cross Origin Resource Sharing

Normally, browsers don’t allow making cross-domain calls due to same-origin policy and we know that. So, what exactly is CORS (Cross Origin Resource Sharing)?

CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the domain which actually rendered that specific web page. CORS is compliant with W3C standards and now ASP.NET Web API has support for it in version 2.

3. OWIN (Open Web Interface for .NET) self hosting

ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi. OwinSelfHost.   According to http://owin.org/
OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

So, according to above description, OWIN is an ideal option for self hosting a web application in a process other than IIS process.

There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web API frameworks.

4. IHttpActionResult

Along with the existing two approaches of creating response from controller action, ASP.NET Web API 2 now supports another way of doing the same. IHttpResponseMessage is basically an interface which acts as a factory forHttpResponseMessage. It’s very powerful because it extensify web api. Using this approach we can compose any specific type of response.

Please follow the link to know how to serve HTML with IHttpActionResult.

5. Web API OData

The Open Data Protocol (OData) is actually a web protocol for querying and updating data. ASP.NET Web API 2 has added support for $expand$select, and $value options for OData. By using these options, we can control the representation that is returned from the server.

  • $expand: Normally, response doesn’t include related entities if we query an OData collection. By using$expand, we can get related entities inline in response.
  • $select: It’s used if we wanted to include subset of properties in response instead of all.
  • $value: It allows to return raw value of the property instead returning in OData format.