Looking deep inside OData Controllers

ASP.NET 4.5 has three different class which we can inherits to implements the controllers: Controller, ApiController and ODataController.

In the latest applications that I implemented, because they were SPA, I used rarely the classic Controller (know as MVC controllers) and I developed a huge number of ApiController and ODataController.

The first ones are used to implements the WEB APIs and the second ones if we want a controller that implements OData protocol.

In this post I want to talk about the main architectural differences between these two typologies and the different behaviour inside the source code.

ApiExplorer

The first difference between them is that the ODataController class has the ApiExplorer setting IgnoreApi=true; this is useful to disable the inspection and don’t retrieve the list of the action to the clients that request it:


[ApiExplorerSettings(IgnoreApi = true)]

This is correct when we talk about of libraries like Swagger, that inspect the entire list of the Web APIs in the application and exposes the documentation about those.

With this default setting, the program by default won’t show the documentation for these controllers.

ODataFormattingAttribute

All the OData Controllers has a custom ODataFormattingAttribute applied by default.

This attribute deal with the parsing of the url parameters and send the results in the correct format.

For example, it’s able to parse the OData $format query option (used to specify the format of the results), format the results like xml, json or raw as well as read the OData Metadata header parameter in the request and define the data to be send.

This attribute override the default action value binder with a PerRequestActionValueBinder and the default negotiator with a PerRequestContentNegotiator as well;  these actions have a specific action selector for the OData requests and a negotiator that uses a per-request formatter for the content negotiation.

ODataRoutingAttribute

The main duty of the ODataRoutingAttribute is to override the default action selector with the specific ODataActionSelector, that meet with the routing conventions and formats.

This selector retrieves the path of the request by using a class ODataPath, that represents the path with additional informations about the Edm type and the entity set.

It retrieves the odata routing conventions from the request as well.

Then, with the path and the conventions it retrieves the action to execute in the controller context.

The last duty is instantiate an ODataProviderValueFactory, a custom class that extendes the ProviderValueFactory that parse and retrieves the routing conventions from the OData url.

Results

The last two stuff added to the ODataController are two methods that send the results to the client.

These methods uses a CreatedODataResult class that format the response according with the OData standards.

Then the header with the location informations is added and the content with the informations about EntitySet, Model, Url is created.

 

 

 

 

Advertisements
Looking deep inside OData Controllers

Managing OAuth 2 authentication with Swagger

In this post I want to talk about a product that could help us to produce documentation about the Web API services implemented in our application.

Swagger is a popular framework that once installed in an ASP.NET application is able to produce documentation about all the Web API implemented in the project.

Furthermore it give us a lot of flexibility and is possible to add some custom filters in order to change the standard behaviours; for example add the OAuth authentication management for the protected applications.

So let’s go to view the steps necessaries to install and configure this framework.

Configuration

The first step is install the package in our project and we can do that with nuget:


Install-Package Swashbuckle -Version 5.6.0

Now we need to add the Swagger configuration in the startup.cs file:


config.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "BaseSPA.Web");
c.OperationFilter<SwaggerFilter>();
c.PrettyPrint();
c.IgnoreObsoleteActions();
}).EnableSwaggerUi();

In the configuration we define the description of the project, we says that we want json in prettify format and we want to ignore obsolete actions.

Furthermore we register a SwaggerFilter, that is a custom filter used to manage the OAuth authentication.

This is the SwaggerFilter implementation:


public class SwaggerFilter: IOperationFilter
 {
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
 var toBeAuthorize = apiDescription.GetControllerAndActionAttributes<AuthorizeAttribute>().Any();

if (toBeAuthorize)
 {
 if (operation.parameters == null)
 operation.parameters = new List<Parameter>();

operation.parameters.Add(new Parameter()
 {
 name = "Authorization",
 @in = "header",
 description = "bearer token",
 required = true,
 type = "string"
 });
 }
 }
 }

First of all we need to implement the IOperationFilter interface with the Apply method.

In this method we check the actions protected with the Authorize attribute; for these, we add a new Authorization parameter that we’ll be showed in the Swagger UI and will be used to set the bearer token.

Test Web API

After compiling the project, we can access the url of the application and append the term swagger at the end of that, like this:


http://localhost/swagger

This is what will be showed:

swagger2

If we open one of the actions available, we notice the Authorization attribute that we have configure above:

swagger5

Now what we need is the bearer token to send to the action and we can retrieve it with Postman; we have to send a post request to the token endpoint configured in the application like this:

swagger1

I send a request with my username, password and grant_type keys and I specify the content type as x-www-form-urlencoded as well.

The response contains the access_token and I can copy it in the field in the swagger UI:

swagger3

That’s all, by sending the request, the application recognize me and it send me the response.

You can find the source code here.

 

 

 

 

 

Managing OAuth 2 authentication with Swagger

Web API in ASP.NET Core

In this post I’ll talk about the Web API in ASP.NET Core and how we can implement a Restful service with this new framework.

One of the main difference in ASP.NET Core is that Web API have an unified class with the classic MVC Controllers.

So the declaration of a Web API in ASP.NET Core is look like this:


public class PostController : Controller
{
}

The attribute of the actions verbs is pretty similar to MVC 5.

We can define the controller route as well and we can do that with the Route attribute:


[Route("api/[controller]")]
public class PostController : Controller
{
}

We can implement an action in the same way as the Web API 2:


[HttpGet("{offset}", Name = "GetPost")]
 public IActionResult Get(int offset)
 {
 var result = _postService.GetPosts(offset, true);

return Ok(result);
 }

With the HttpGet attribute we can specify the verb of the method, the parameters and the action url.

So far so good, now there is the last question about this topic, that is the content negotiation.

Since ASP.NET Core MVC and Web API frameworks are unified, with the attribute Produces we can define the response content type for the controllers.

So, if we want to return a content type in json format, we need to apply this attribute:


[Produces("application/json")]
[Route("api/[controller]")]
public class PostController : Controller
{
}

With this attribute the content type of the request will be application/json, otherwise the controller will returns a response 415 – Unsupported media type.

The source code of the topic is here.

 

Web API in ASP.NET Core