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>.

Goodbyes are hard…..

Yes, Goodbyes are hard. After almost 5 years at Infragistics, I am moving on and seeking other opportunities. I must say these years were the best years of my life.


clip_image002

At Infragistics, I was a Developer Evangelist. My job was to engage developers, create more awareness with them around Infragistics’ Ignite UI product, and to help them to be successful.   Here are some of the things I accomplished : 

  • I created a developer community for Infragistics in India
  • I helped customers to learn and implement their solutions using Ignite UI
  • I delivered many workshops and talks across India for customers on JavaScript,  Angular, Ignite UI, ASP.NET MVC and more.
  • I created samples and customer POCs
  • I wrote articles for Infragistics blog. You can read them here

As a remote employee, I worked with various teams, managers, and regions. Based on that experience, I can say that Infragistics is one of the best employers and lead by true thought-leaders. They truly believe in making their customers successful and take care of their employees. I am grateful for my time at Infragistics, and want to send a special thanks to Senior Vice President Jason Beres for his trust in me, and giving me the opportunity. 

image

Other people I would like to thank is Director of Product Developer Konstantin Dinev , Managing Director of APAC Ken Azuma , Director of India Rohit Gaur , and my first manager Anand Raja for their constant support.

What’s Next?

I have been a Developer Evangelist for the last 7 years, helping Progress Telerik and Infragistics create their developer base in India. My forte is evangelism and I want to continue helping in reaching and educating developers and in creating community.

If you are looking for someone to help you engage with, enable, and excite your developers, feel to reach me at debugmode[at]outlook.com or tweet me at @debug_mode

 

C# Basics: Delegates

Delegates are one of the most used features of C#. It allows you to pass a function as of function pointer. It is kind of same as function pointer of C++.

Put simply, delegates are the same as a function pointer of C ++. It refers to another function.

As noted in Microsoft official documentation:

“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”

Before get deeper into technical jargon about delegates, let us create first a delegate.

Let us talk through the above code.

  1. Just before main function in comment #1, we are declaring a delegate named AddDelegate. The signature of a delegate is very important, because a delegate can only refer functions matching the same signature.
  2. We created delegate with return type set to integer and it takes two input integer parameters.
  3. In comment # 2, we are instantiating delegate and passing add function as reference.
  4. In comment # 3 invoking the delegate.

On running above, you should get output as shown in the below image:

One important thing you need to keep in mind is that the signature of delegates must match with the signature of the function pointed by the delegate. Not only signature, but also return type should match.

Read full article on the Infragistics blog

Simplest way to share data between two unrelated Components in Angular

In Angular, it is essential to know how components communicate with each other. If you use a component inside another component, they create a parent child relationship.  In such a scenario, parent and child components communicate to each other in following ways:

  • @Input()
  • @Output()
  • Temp Ref Variable
  • ViewChild and ContentChild

You can learn in detail about @Input here   and @Output here. In this blog post, you will learn how data can be shared between components that are not related to each other using Angular Service.

To understand this using an example, create a service.  In the service, create a variable called count.  Service will share value of count variable across the components. Before we create count variable, let us talk about requirement again. We want all components to access last updated value of the data shared using the service.

For this, we have to wrap the count variable in RxJS subjects. To be precise let us use BehaviorSubject.

We are using BehaviorSubject for the following reasons:

  1. Data from the service should be multicasted. Each consumer component should access the same copy of the data. For this purpose, BehaviorSubject is used.
  2. We are not using observables, as they are unicast in nature. Subscribers will have their own copy of data.
  3. BehaviorSubject stores current value. Therefore, component will always read current value of data stored in BehaviorSubject.

Read full article on the Infragistics blog

Type of Undeclared Variable in JavaScript: What is it?

 

Have you ever thought, what is type of undeclared variable in JavaScript? I know, the first thing that might come to mind is: how can an undeclared variable have a type? Yes, in JavaScript it is possible.

To understand it, let us start with understanding types in JavaScript. There are seven built in types in JavaScript. They are as follows:

  1. null
  2. undefined
  3. boolean
  4. number
  5. string
  6. object
  7. symbol (added on ES6)

Each variable with assigned value has a type. Let us consider the code listed below:

As you can see in the above snippet, if there is no value assigned then type of variable is undefined.

So far so good, we saw that variable with no assigned value is undefined.  Let us consider the next code snippet:

We have created a variable koo and have not assigned any value to it.  Now both value and type of koo are set to undefined.

Read full article on the Infragistics blog

Simplifying Angular CLI for beginners

So you want to write your first Angular application, however setting up even a ‘Hello World’ Angular application is not easy. It requires many steps such as:

  • Setting up a TypeScript compiler, if you choose to use TypeScript
  • Configuration of Webpack or other module loader
  • Setting up local web development server
  • Installing and configuring dependencies
  • Configuring Unit Test environment
  • Configuring End to End Test environment
  • Working with Continuous Delivery
  • Working with Continuous Integration and many more

You can perform all these tasks manually, but this will require a strong understanding of all these concepts and will make starting a new project very time consuming. To solve this problem, Angular comes with the Angular Command Line Interface (CLI).

Learn more about it here: https://cli.angular.io/

All these tasks are taken care of by Angular CLI, which is a command line tool for creating, testing, and deploying Angular apps. It is recommended to use Angular CLI for creating Angular apps, as you do not need to spend time installing and configuring all the required dependencies and wiring everything together. It provides you with many boilerplates and saves your time.

It uses Webpack to include all the packaging, the loading module, importing functionality, BrowserLink and more. The entire Webpack configuration is done completely by CLI so you don’t have to worry about it. It also configures Jasmine and Karma for unit tests and TypeScript complier to transpile TypeScript file to JavaScript etc.  Let us see how we can work with Angular CLI.

Learn full article on the Infragistics blog

Completed 11 Years working in the Industry

image

I am very excited to share that today I completed 11 years working in the industry. It has been a learning and good challenging journey for me. During last 11 years, I have lived in three different cities and worked on six different technologies. I started my career as Software Engineer and currently working as a Developer Advocate for Infragistics.

image

Below in tabular form you can find my work experiences:

image

Besides working for various organization, since very beginning of my career, I have been writing articles. So far, in last 11 years I have authored more than 900 articles. You can read them on my blog: https://debugmode.net/.

I also authored a book on Angular called Angular Essentials.

clip_image002

In India, you can get it here: https://www.amazon.in/Angular-Essentials-Dhananjay-Kumar/dp/9388511247/ref=sr_1_1?ie=UTF8&qid=1553590814&sr=8-1&keywords=angular+essentials

Outside India, you can get it here : https://www.amazon.com/Angular-Essentials-Dhananjay-Kumar-ebook/dp/B07NL5RSDF/ref=sr_1_1?keywords=angular+essentials&qid=1553590883&s=gateway&sr=8-1

Due to my contributions, Microsoft awarded me prestigious Microsoft MVP Award on 1 April 2010. Since then, I have been getting Microsoft MVP Award each year. So far, I have been awarded 9 times. You can find my MVP profile here: https://mvp.microsoft.com/en-us/PublicProfile/4028360?fullName=Dhananjay%20Kumar

image

After getting Microsoft MVP Award, I started participating as speakers. I got chance to speak in various Microsoft User Group meets and conferences. So far, in last 11 years, I have delivered 77 free talks or workshops. You can find details about them here: https://debugmode.net/speaking/.

In 2016, I founded offline community geek97 , thorough that we hosted free workshops  in various Indian cities. We also mentor young talent to become speaker and community contributor.

Geek97 also organizes India’s largest Angular Conference ng-India https://www.ng-ind.com/ . You can see summary video of last ng-India here: https://www.youtube.com/watch?v=ccNBr-LX6tQ

image

I have been enjoying working with Infragistics for last 4 years, and in coming years, I am aspired to work on JavaScript language, PWA, Angular and AI. I hope, I am able to add values in your professional life through my evangelism, writing, teaching, and ng-India.

Thanks

Dhananjay Kumar

Winner of 9 Microsoft MVP Awards

Organizer ng-India