All about types of Action Results in the Web API

While building an API, the client should receive a proper and descriptive HTTP response message for each request. The Web API provides a very simple approach to achieve this.  A Web API controller action can return the following types:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Other types, such as IEnumerable, object, collections, etc.

action result type

To test these different types and HTTP response message associated with them, I will use REST client tool Postman.

The void type

If the return type is set to void, Web API returns an empty HTTP response message with status code 204 means no content.  Let us create an action, which returns void,

In the Postman, on performing HTTP Post operation, you will get response as shown next:

typeinactionresult2

The HttpResponseMessage type

HttpResponseMessage type represents a HTTP response message which encapsulates data and the status code. Besides status code, you can also set other properties such that,

  • Content
  • Headers
  • IsSucessStatusCode
  • ReasonPhrase
  • RequestMessage
  • Version

You can return HttpResponseMessage with certain properties set as shown below:

 

So, /api/data returns HtppResponseMessage, which has content, status code, Reason Phrase to be sent with the code, and cache control set. In the postman, you will get a response header as shown below. Also, you will notice that the status code contains Reason Phrase, “Data is processed.”

typeinactionresult3

Also, the response would be cached for 20 milliseconds. You can also use the HttpResponseMessage type to send data into the response body. It uses media formatter to serialize the data in the format passed as the accept header of the HTTP request.  For example, training data can be sent in the body of HttpResponseMessage as shown below,

Now, in the postman client, if you set Accept Header of Request to application/XML as shown in below image,

typeinactionresult4

In the response body, you will get training data from the API serialized as XML,

typeinactionresult5

Whereas if you set Accept Header of Request to application/JSON as shown in below image,

typeinactionresult6

In the response body, you will get training data from the API serialized as JSON,

typeinactionresult7

The IHttpActionResult type

The third type is IHttpActionResult, which was introduced in Web API 2.0. It provides, a factory to construct an HttpResponse message. It allows you to construct HTTP responses in a separate class, such that controllers can be better unit tested.

You can use IHttpActionResult in two ways:

  1. Implement it in a separate class to construct the HTTP response.
  2. Directly Use IHttpActionResult defined in System.Web.Http.Results namespace.

Often, you can use IHttpActionResult to return a particular data in this case training as shown below,

IHttpSActionResult from System.Web.Http.Results provides two methods to return result from the action.

  1. NotFound
  2. Ok

As you see, GetTraining action returns data wrapped in Ok method, or NotFound, if training with given id does not exist.

In the postman client, if you pass id value to 1 as shown in the below image, you will get an HTTP response with status 404 Not Found, as there is no training with id 1 exist.

typeinactionresult8

You can also create an HTTP response message in a separate class.  By doing that, you hide low-level details of HTTP response message construction from the controller class and can also reuse the code to construct an HTTP response message. To do this,

  • Implement IHttpActionResult interface in the class
  • Define ExecuteAsync method

We can implement IHttpActionResult to return a list of trainings in the HTTP response message, as shown below:

We are, setting various properties of the HttpResponseMessage in the ExecuteAsync method. To return list of trainings as content of the HTTP response message, we are creating object of ObjectContent and using JSONMediaTypeForammter to convert list of training in a JSON format.

Now you can use newly created TrainingDataResponse in the controller class as shown below:

Now you can test it in the postman client as shown in the image below,

typeinactionresult9

Other Types

Besides the above three types, you can use any other types such as IEnuenrable<T>, List<T>, etc. To return them as HTTP response Web API uses the media formatter to serialize the returned data. Web API will write the serialized data in the body of the Http response, and set the status to 200.

Below action returns trainings, which is serialized by Web API,

In the postman, you can test it as shown below:

typeinactionresult11

Conclusion

These are the types supported by Web API. You should use them as per your requirement.  For example, to construct low level details of HTTP response message, use the type HttpResponseMessage, and to send serialize data with status code 200, use the other types such as IEnumerable<T>.

How to write Unit Tests for a .NET Core Application

Read full article on the Infragistics blog

Writing unit tests is a good software engineering practice. In this article, we will learn how to create a C# .NET Core application while adhering to the Test Driven Development (TDD) approach. In the TDD approach, before implementing a functionality, you write a unit test for it. For example, if you want to write a function to add two numbers, first you’ll write a failed unit test and then implement the functionality to pass the test.

In this post, we’ll create a Calculator Application. To start, let’s follow the folder structure as outlined below:

· CalculatorApp – Solution

· CalculatorApp.Services – Application project

· CalculatorApp.Services.Tests – Test project

You can use Visual Studio to create projects; however, in this post, I will use .NET Core commands to create my projects, add tests, and run tests. You can also use MSTest or NUnit to write unit tests, but in this example, I’ll use xUnit and dotnet test to write and run my Unit Tests.

Let’s start by opening a command shell and follow along:

 Creating the Application project

To start, you’ll need to create a directory called CalculatorApp. Keep in mind that you can follow any naming convention you’d like for directories, but if you’d like to follow along with this post, I would recommend following the same directory name. So, let’s create the CalculatorApp directory and navigate to it.

Inside the CalculatorApp directory, we are going to create a new solution by running the following command:

dotnet new sln

After successfully running the command, you should get the message “The Template Solution File was created successfully”. Also inside the CalculatorApp directory, you will find a file named calculatorapp.sln.

Next, create a directory called CalculatorApp.Services. This directory will keep the application sources i.e. all classes of the calculator application. Navigate to the Calculatorapp.Services directory and create a class library by running the following command:

dotnet new classlib

After successfully running this command, you should get the message “The Template Class Library was created successfully”. You’ll also find a file named calculatorapp.services.csproj inside the CalculatorApp.Services directory. Next, you need to add this class library project to the calculatorapp solution. To do this, navigate back to the calculatorapp directory, and run the command:

dotnet sln add .\calculatorapp.services\calculatorapp.services.csproj

After successfully running the command, you should get the message “Project added to the solution”.

Inside the CalculatorApp.Services folder, you will find a class Class1 – rename it to Calculator and modify the class as shown in the listing below:

Calculator.cs

You’ll notice in the above listing that the Add and Sub functions are not implemented. First, we will write a unit test and then implement these functionalities.

Creating the Test project

To add test projects, create a directory called CalculatorApp.Services.Tests and navigate to the directory. In this directory, we will create an MS Test project by running the following command:

dotnet new mstest

This command creates the test project which uses MS Test as the test library. Once the test project is created, add the source project library in the test project. To do that, run the command:

dotnet add reference ../CalculatorApp.Services/CalculatorApp.Services.csproj

This command will add a reference of the CalculatorAppService project into the test project. After adding the reference, add the test project to the solution by navigating to the calculatorapp root directory, and run the command:

dotnet sln add .\CalculatorAppServices.tests\CalculatorAppServices.Tests.csproj

This command will add the test project to the solution. After successfully running the command, you should get the message “Project added to the solution”.

Writing Unit Tests

So far, we’ve created the application source project and a test project. In the application source project, there are unimplemented functions. Now let us write tests for these functions.

In the Test project, I have renamed the file UnitTest1.cs to Calculator.Test.cs and the class name to CalculatorTest. In the constructor of CalculatorTest, we need to create an object of the Calculator class. This can be done as shown in the listing below:

Calculator.Test.cs

Unit Test for Add function

In the CalculatorTest class, add a unit test method to test the add functionality as shown in the listing below:

To run the test, navigate to the CalculatorApp.Services.Tests directory and execute the command:

dotnet test

You’ll get a ‘test failed’ output because the Add function is not implemented, as shown in the image below:

image

To pass the test, implement the Add function in the Calculator class as shown in the listing below:

To run the test now, navigate to the CalculatorApp.Services.Tests director and execute the command:

dotnet test

As output, you will get the ‘test passed’ message as shown in the image

Read full articles on the Infragistics blog

How to Write Your First .NET Core 2.0 Application

Read full article on the Infragistics blog here

Microsoft .NET Core is a cross-platform open source software development framework that can be used to build applications for mobile, Windows, and the web. You can learn more about .NET Core here, but in this blog post, we’ll walk you through how to create and publish a .NET Core application for Windows.

To work with .NET Core, first you need to install it from here . While you can use any IDE to create a .NET Core application, I am going to use the Visual Studio 2017 Enterprise version. If you do not have Visual Studio installed, you may want to try the community edition, which can be found for free here.  Once the environment is set, launch Visual Studio and create a new project by selecting File->New Project-> Visual C#-> .NET Core-> Console App. Besides C#, a .NET Core application can be used in other languages like Visual Basic.

After successfully creating your project, you will see there is already template code in the Program.cs file which looks like listing 1, shown below:

Read full article on the Infragistics blog here