Tuesday, April 29, 2014

Manage WebApi Response using Media Types of MediaTypeFormatters

In this article I’ll explore different ways to manage Manage WebApi Response using Media Types with help of Media Type Formatters.

From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime (CLR) type into a format that can be transmitted over HTTP. The default format I are either JSON or XML

A media type formatter, which is an object of type MediaTypeFormatter, performs the serialization in the ASP.NET Web API pipeline. Consider a simple action method handling GET in an ApiController:

 

  1: [HttpGet]
  2: public Employee FetchEmployeeById (int id)
  3: {
  4: return list.First(e => e.Id == id);
  5: }
  6: 
Content negotiation is the process by which ASP.NET Web API chooses the formatter to use and the media type for the response message.

Whenever we request a url, WebApi checks the following four items before deciding on the media formatter to use.

1. Media type mapping: Every MediaTypeFormatter has a collection of MediaTypeMapping values. A MediaTypeMapping allows you to map the request or response messages that have certain characteristics to a media-type. There are four out-of-box media type mappings: QueryStringMapping, UriPathExtensionMapping, RequestHeaderMapping, and MediaRangeMapping. These respectively map a query string parameter, URI path extension, request header, and media range to a media type. As an example, defining a QueryStringMapping with a parameter name of fmt and a value of json and media-type of application/json will let ASP.NET Web API choose JsonMediaTypeFormatter, if the query string has a field fmt with a value of json, such as this: http://localhost:57888/api/employees/001?fmt=json.

2. Media type as specified in the Accept request header.

3. Media type as specified in the Content-Type request header.

4. If there is no match so far, the conneg algorithm goes through the MediaTypeFormatter Objects defined in the config and checks if a formatter can serialize the type by calling the CanWriteType method. The first formatter that can serialize the type is chosen.Kindly refer this link to understand CanWriteType as given below:

WebApi: MediaTypeFormatters in WebApi

Now we use an example and see the behavior of request with Media Type.

Kindly can also visit these links to know more about WebApi.

WEBAPI: EXECUTION OF RPCSTYLE ACTION METHOD IN WEBAPI USING MVC4

WEBAPI PATCH UPDATE USING FROMBODY PARAMETER IN WEBAPI USING MVC4 TEMPLATE

WebApi Configuration over Convention using MVC4 template

Let’s create a sample application and achieve this step by step.

Step 1: Let's first create a sample web application using an ASP.NET MVC 4 Web Application and name it as you choose; I used WebApiDemo as shown in the image below:


image


 


Step2: Click ok and choose Web API option from the templates shown in wizard window.

image


Step3: You’ll find the application structure as shown below at first sight.

image

 

Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤Controller and give a name of EmployeesController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click Add, as shown in Figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.Kinldy add the following code into EmployeesController class.

image

 

  1: public static IList<Employee> listEmp = new List<Employee>()
  2:         {
  3:             new Employee()
  4:             {
  5:                 ID =    , FirstName="Sachin", LastName="Kalia"
  6:             },
  7:              new Employee()
  8:             {
  9:                 ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
 10:             },
 11:             new Employee()
 12:             {
 13:                 ID =003, FirstName="Ravish", LastName="Sindhwani"
 14:             },
 15:              new Employee()
 16:             {
 17:                 ID =004, FirstName="Amit" ,LastName="Chaudhary"
 18:             },
 19:              new Employee()
 20:             {
 21:                 ID =004, FirstName="Anshu" ,LastName="Aggarwal"
 22:             },
 23: 
 24:         };
 25: 

Step 5: Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class

to add a new class with a name of Employee.

image

 

After creating the Employee.cs class, kindly add the following code into this class.

  1: public class Employee
  2: {
  3: public string ID { get; set; }
  4: public string FirstName { get; set; }
  5: public string LastName { get; set; }
  6: public string Department { get; set; }
  7: }
  8: 
  9: 
Press F5 and run your application it will show the below image:

image

 

Great WebApi is up and running.

Steps to get response of WebApi in Json format.

Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab and specifying Accept: application/json in the Request Headers text box.

image

 

It will respond in json format after accepting the Accept: application/json.To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window

 

image

Now we change the Media Type to Accept: application/xml, after putting this in the request WebApi will respond in xml format. Let’s see in example.

Steps to get response of WebApi in XML format:


Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab specifying Accept: application/xml in the Request Headers text box.

Now press Execute as depicted below in image.

image

It will respond in xml format after accepting the Accept: application/xml.

To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window.

image

Steps to get response of WebApi on basis of quality factor:

Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab and specifying Accept: application/xml;q=0.2, application/json;q=0.8 in the Request Headers text box.

Now press Execute as depicted below in image.

image

It will respond in json as it has quality factor greater than xml.

To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window

image

Now slightly change the request and specifying Accept: application/xml; q=0.8, application/json; q=0.2In the Request Headers text box.

image

It will respond in xml format due to xml has higher priority than json in this specific request. Sounds great.

Important note: you can also identify the response after looking at the icon of response as shown in below image.

image

 

Difference between accept and content-type http headers?

As you correctly note, the Accept header is used by HTTP clients to tell the server what content types they'll accept. The server will then send back a response, which will include a Content-Type header telling the client what the content type of the returned content actually is.However, as you may have noticed, HTTP requests can also contain Content-Type headers. Why? Well, think about POST or PUT requests. With those request types, the client is actually sending a bunch of data to the server as part of the request, and the Content-Type header tells the server what the data actually is (and thus determines how the server will parse it).In particular, for a typical POST request resulting from an HTML form submission, the Content-Type of the request will normally be either application/x-www-form-urlencoded or multipart/form-data.

Conclusion: In this article we looked into how to Manage WebApi Response using Media Types of WebApi those are very much essential from the user's perspective.

Hope it will help you somewhere down the line J

Keep coding and Smile Smile

Thanks

Sachin Kalia

Thursday, April 24, 2014

WebApi: MediaTypeFormatters in WebApi

WebApi: MediaTypeFormatters in WebApi

In this article I’ll share my Media Type formatting in WebApi.

From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime (CLR) type into a format that can be transmitted over HTTP. The default format I are either JSON or XML

A media type formatter, which is an object of type MediaTypeFormatter, performs the serialization in the ASP.NET Web API pipeline. Consider a simple action method handling GET in an ApiController:

public Employee Get(int id)

{

return list.First(e => e.Id == id);  clip_image002   clip_image001

}

This method returns a CLR object of type Employee. In order for the data contained in this object to be returned to the client in the HTTP response message, the object must be serialized. The MediaTypeFormatter object inthe ASP.NET Web API pipeline performs this serialization. It serializes the object returned by the action method into JSON or XML, which is then written into the response message body. The out-of-box media formatters that produce JSON and XML are respectively JsonMediaTypeFormatter and XmlMediaTypeFormatter, both deriving from MediaTypeFormatter. The process through which the MediaTypeFormatter is chosen is called content negotiation, also known as conneg.

A resource can have one or more representations. When you issue a GET to retrieve a resource, such as the employee with ID 12345, the response message contains the representation of the resource e.g. any value that specific action returns. The Web API indicates how the resource is represented in the response through the Content-Type response header. The Accept request header can be used by a client to indicate the set of preferred representations for the resource in the response.

Default the ASP.NET Web API framework supports two media or content types: JSON and XML.If you send a request with Accept: application/json, the response message will be JSON and Content-Type will be application/json. Similarly, if you send a request with Accept: application/xml, the response message will be XML. You can also specify a quality value indicating the relative preference. The range is 0–1, with 0 being unacceptable and 1 being the most preferred. The default value is 1. For example, if you send the request header Accept: application/json; q=0.8, application/xml;q=0.9, the response message will be XML,because application/xml has a quality value of 0.9, which is higher than the quality value of 0.8 specified for application/json.

Now we take an example and list out the default MediaTypeFormatters:

Kindly can also visit these links to know more about WebApi.

WEBAPI: EXECUTION OF RPCSTYLE ACTION METHOD IN WEBAPI USING MVC4

WEBAPI PATCH UPDATE USING FROMBODY PARAMETER IN WEBAPI USING MVC4 TEMPLATE

WebApi Configuration over Convention using MVC4 template

Let’s create a sample application and achieve this step by step.

Step 1: Let’s first create a sample web application and using ASP.NET MVC 4 Web Application and named It with your choice as I gave WebApiDemo shown in depict image below:

clip_image004

Step2: Click ok and choose Web API option from the templates shown in wizard window.

clip_image006

Step3: You’ll find the application structure as shown below at first sight.

clip_image008

Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤Controller and give a name of EmployeesController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click Add, as shown in Figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.Kinldy add the following code into EmployeesController class.

   1:  public class EmployeesController : ApiController
   2:      {
   3:          public static IList<Employee> listEmp = new List<Employee>()
   4:          {
   5:              new Employee()
   6:              {
   7:                  ID =001, FirstName="Sachin", LastName="Kalia"
   8:              },
   9:               new Employee()
  10:              {
  11:                  ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
  12:              },
  13:              new Employee()
  14:              {
  15:                  ID =003, FirstName="Ravish", LastName="Sindhwani"
  16:              },
  17:               new Employee()
  18:              {
  19:                  ID =004, FirstName="Amit" ,LastName="Chaudhary"
  20:              },
  21:   
  22:          };
  23:      }



clip_image010

Step 5: Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class

to add a new class with a name of Employee.

clip_image012

After creating the Employee.cs class, kindly add the following code into this class.


   1:  public class Employee
   2:  {
   3:   
   4:  public string ID { get; set; }
   5:   
   6:  public string FirstName { get; set; }
   7:   
   8:  public string LastName { get; set; }
   9:   
  10:  public string Department { get; set; }
  11:   
  12:  }
  13:   


Modify the Register method in WebApiConfig in the App_Start folder and add some code segment into this to list out the default MediaTypeFormatters as shown in below image:


clip_image014

Press F5 and run your application it will show the below image:

clip_image016

Great WebApi is up and running.

Now look at the output window of your application, it gives you the details of each line which we’ve placed into the WebApiConfig.cs file.

clip_image017

From the serialization point of view, the last two media type formatters can be ignored, since they cannot write any type. The first two, JsonMediaTypeFormatter and XmlMediaTypeFormatter, are the important ones. They are the media formatters that produce JSON and XML resource representations in the response

Conclusion: In this article we looked into default MediaTypeFormatters of WebApi, which are very much essentials from user perspective.


You can touch base with me on DotnetPiper.

Hope it will help you somewhere down the line J

Keep coding and Smile Smile

Thanks

Sachin Kalia





Tuesday, April 22, 2014

Extension Helpers Method in MVC

Extension Helpers Method in MVC

This article is more about the Custom Helpers and Extension Helper method in MVC with Razor View Engine.

There are lots of ways to create your own helpers using Razor syntax. I am using one of them. Helper method is an optimum way to achieve functionality.

So let’s start and create Helper method.

First we’ll start with Extension method syntax. I have created a sample application and it has HtmlHelpers.cs exist into HtmlHelpers folder.

clip_image002

Open HtmlHelpers.cs file and you will find the given below code snippet, which is an extension method which takes two parameters and does its operation to remove string using substring method.

clip_image004

So far we have declared extension method, now time is to use it into our View page (.cshtml).I’ll use it on Verify.cshtml page .Here is the code snippet of that page.

clip_image006

As you can see we are using RemoveString () Helper method on Verify.cshtml page, which cater the raw string (raw string as declared into ViewBag.Message property) with help of two parameters being passed.

Now let’s run this and see the execution:

clip_image008

Notice that it took the complete string which we’ve passed like @Html.RemoveString(ViewBag.Message as string, 20) and perform the code down the level.

Again Press f5 and see the result.

clip_image010

Notice that it only gives you "Welcome to C#Corner” out of complete string.

So this is how we can create Helper method on demand in Razor view Engine. Sample application is attached as a reference.

Stay Happy Stay Coding Smile

 

You can touch base with me here Sachin Kaila Profile

Monday, April 21, 2014

Remove Ambiguity of Controller Names in MVC application

In this article I am sharing my thoughts on to create routing system in MVC application and terminology being used.

Here we go:

RouteData: This mechanism is used to examine an incoming URL and then decide which controller and action the request is need to be send.

Open your visual studio, click on New Project and select ASP.NET MVC3 Web Application:

clip_image002

Specify the name of your first application like your desire and click ok.

New window will appear ,from that window I picked up Intranet application whilst many options are there .Another intersting fact that there is a dropdown named as View Engine I seleccted Razor which is more specific to MVC 3 and MVC 4 and keep a checkbox “create a new unit test” unchecked.

clip_image004

Click on ok button .

The given below depict screen is default one comes after clicking on OK button.Hvaing multiple folder’s.

clip_image006

We need to make some amendments into this to understand how routing works. Application_Start method is responsible for registering the RegisterRoutes method . This Application_Start method is called by ASP.NET platform when the application is started fisrt.

To explore more on routing in MVC, Have a look into the link

http://www.c-sharpcorner.com/UploadFile/97fc7a/routing-in-mvc3-application/

Let’s see what happen when we run our application first time with default routing settings.

clip_image008

Which fulfills this route system?

clip_image010

Whenever we hit this url “http://localhost:60346/” ,First it jumps into the given class and ask for the action method names as “verify” as in depict image down level:

clip_image011

Let’s look into the image below to understand how we co-relate the namespaces of .cs file and routing path defined into global.asax.If you notice the red encircled box ,both pointing the same .namespace MVCSample.Controllers,It means whenever such url will hit by user having the same pattern defined in route will hit this class first.

clip_image013

If I remove namespce parameter from route then it throws the given below error:

clip_image015

This error comes because we’ve defined two controller with same name in a solution.Which rasie confusion which should be called here.

clip_image017

To over come on this issue we necessitated to place controller name with Complete namespace.

Here we define the route to resolve such issue as image shows:

clip_image019

After defining the route into an application runs in perfect mode :

clip_image020

If you hit the next url http://localhost:60346/Views/Register/RegisterAction ,it jumps into the different controller under MVCSample.Register namespace,

clip_image021

And gives you the result accordingly as below:

clip_image023

So using namespace parameter into routing made very much convenient for enduser to solve such issue.

Hope this will help you lot of geeks .Sample application been attached as reference.

Enjoy MVC and Routing.

Kindly inform me if having any query.

You can also touch base with me on Sachin Kalia Profile on C#Corner

Chees .Net Smile

Sachin Kalia

Thursday, April 17, 2014

WebApi: Execution of RPCStyle action method in WebApi using MVC4

In this article I’ll share my thoughts on How to implement RPC Style action method in WebApi using MVC4.

In simple words RPC style is a way to call any method via URL, whereas RPC stands for Remote procedure call.

Kindly can also visit these links to know more about Configuration over Convention in WebApi.

WEBAPI PATCH UPDATE USING FROMBODY PARAMETER IN WEBAPI USING MVC4 TEMPLATE

WebApi Configuration over Convention using MVC4 template

I’ve defined a method named as, RPCStyleMethodFetchEmployee.To call this method from we need to put the URL in browser http://localhost:57888/api/employees/RPCStyleMethodFetchEmployee/

For this RPC-style selection of an action method to work, you have to make an entry in the WebApiConfig.cs file under App_Start folder.

Kindly make this entry in WebApiConfig.cs under Register method under WebApiConfig.cs

clip_image002

 

                                                                                                                                                                                                                                                                                                                                                                 clip_image003

The only difference now is that the action method that handles the GET request is GetEmployeeRpcStyle, which is part of the URI (http://localhost:57888/api/employees/RPCStyleMethodFetchEmployee/) route data. Review theURI you used. It is no longer in the REST style. The action method is also part of the URI and is in RPC-style.

Let’s create a sample application and achieve this step by step.

Step 1: Let’s first create a sample web application and using ASP.NET MVC 4 Web Application and named It with your choice as I gave WebApiDemo shown in depict image below:

clip_image006

Step2: Click ok and choose Web API option from the templates shown in wizard window.

clip_image008

Step3: You’ll find the application structure as shown below at first sight.

clip_image010

Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤Controller and give a name of EmployeesController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click Add, as shown in Figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.Kinldy add the following code into EmployeesController class.


public static IList<Employee> listEmp = new List<Employee>()
        {
            new Employee()
            {
                ID =001, FirstName="Sachin", LastName="Kalia"
            },
             new Employee()
            {
                ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
            },
            new Employee()
            {
                ID =003, FirstName="Ravish", LastName="Sindhwani"
            },
             new Employee()
            {
                ID =004, FirstName="Amit" ,LastName="Chaudhary"
            },

        };

clip_image012

Step 5: Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class

to add a new class with a name of Employee.

clip_image014

After creating the Employee.cs class, kindly add the following code into this class.

public class Employee

{

public string ID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

}

Now I’ve declared two methods named as RPCStyleMethodFetchEmployee

,RPCStyleMethodFetchFirstEmployees, which follows the convention based (starts with Get, PUT, POST, Delete and PATCH) approach to call methods of WebApi

clip_image016

Press F5 and run your application it will show the below image:

clip_image018

Great WebApi is up and running.

Kindly paste this url (http://localhost:57888/api/employees/RPCStyleMethodFetchFirstEmployees ) into browser and press enter, it will reach into your code segment. Where you’ve set a debugger point.

clip_image019

Press F5 again and see the result as shown below in image.

clip_image021

 

                                                                                                                                                                                                                                                                                                                                                                       clip_image003[1]

The only difference now is that the action method that handles the GET request is GetEmployeeRpcStyle, which is part of the URI http://localhost:57888/api/employees/RPCStyleMethodFetchFirstEmployees route data. Review theURI you used. It is no longer in the REST style. The action method is also part of the URI and is in RPC-style.The same process is for second action method declared in employees controller class.

 

Conclusion: In this article we looked into RPC Style action method call in WeApi.

Hope it will help you somewhere down the line Winking smile

Keep coding and Stay Happy Smile

Thanks

Sachin Kalia