Asp.Net Web API with 50 Plus Interview Questions

Spread the love

What is Web API?

Before we understand what is Web API, let’s see what is an API (Application Programing Interface).

As per Wikipedia’s Definition of API: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications.

To put it in simple terms, API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.

Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol. It is a concept and not a technology. We can build Web API using different technologies such as Java, .NET etc. For example, Twitter’s REST APIs provide programmatic access to read and write data using which we can integrate twitter’s capabilities into our own application.

ASP.NET Web API

The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view. It is like a webservice or WCF service but the exception is that it only supports HTTP protocol.

ASP.NET Web API Characteristics

  1. ASP.NET Web API is an ideal platform for building RESTful services.
  2. ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline
  3. ASP.NET Web API maps HTTP verbs to method names.
  4. ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.
  5. ASP.NET Web API can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
  6. ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.

ASP.NET Web API Versions

Web API VersionSupported .NET FrameworkCoincides withSupported in
Web API 1.0.NET Framework 4.0ASP.NET MVC 4VS 2010
Web API 2 – Current.NET Framework 4.5ASP.NET MVC 5VS 2012, 2013

ASP.NET Web API vs WCF

Web APIWCF
Open source and ships with .NET framework.Ships with .NET framework
Supports only HTTP protocol.Supports HTTP, TCP, UDP and custom transport protocol.
Maps http verbs to methodsUses attributes based programming model.
Uses routing and controller concept similar to ASP.NET MVC.Uses Service, Operation and Data contracts.
Does not support Reliable Messaging and transaction.Supports Reliable Messaging and Transactions.
Web API can be configured using HttpConfiguration class but not in web.config.Uses web.config and attributes to configure a service.
Ideal for building RESTful services.Supports RESTful services but with limitations.

When to choose WCF?

  • Choose WCF if you use .NET Framework 3.5. Web API does not support .NET 3.5 or below.
  • Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named pipe.
  • Choose WCF if you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security.
  • Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange patterns.

When to choose ASP.NET Web API?

  • Choose Web API if you are using .NET framework 4.0 or above.
  • Choose Web API if you want to build a service that supports only HTTP protocol.
  • Choose Web API to build RESTful HTTP based services.
  • Choose Web API if you are familiar with ASP.NET MVC.

Web API Controllers

We created Web API with MVC project in the previous section where it generated a simple controller. Here, you will learn about Web API Controller in detail.

Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.

Web API controller is a class which can be created under the Controllers folder or any other folder under your project’s root folder. The name of a controller class must end with “Controller” and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.

The following is a simple controller class added by visual studio by default when we created a new Web API project in the Create Web API Project section.

Example: Simple Web API Controller

 Copy

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

namespace MyWebAPI.Controllers

{

    public class ValuesController : ApiController

    {

        // GET: api/values

        public IEnumerable<string> Get()

        {

            return new string[] { “value1”, “value2” };

        }

        // GET: api/values/5

        public string Get(int id)

        {

            return “value”;

        }

        // POST: api/values

        public void Post([FromBody]string value)

        {

        }

        // PUT: api/values/5

        public void Put(int id, [FromBody]string value)

        {

        }

        // DELETE: api/values/5

        public void Delete(int id)

        {

        }

    }

}

As you can see in the above example, ValuesController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.

Based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), Web API decides which Web API controller and action method to execute e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API.

The following figure illustrates the significance of Web API controller and action methods.

Web API Controller Overview

If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.

Example: Simple Web API Controller

 Copy

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

namespace MyWebAPI.Controllers

{

    public class ValuesController : ApiController

    {

        [HttpGet]

        public IEnumerable<string> Values()

        {

            return new string[] { “value1”, “value2” };

        }

        [HttpGet]

        public string Value(int id)

        {

            return “value”;

        }

        [HttpPost]

        public void SaveNewValue([FromBody]string value)

        {

        }

        [HttpPut]

        public void UpdateValue(int id, [FromBody]string value)

        {

        }

        [HttpDelete]

        public void RemoveValue(int id)

        {

        }

    }

}

Web API Controller Characteristics

  1. It must be derived from System.Web.Http.ApiController class.
  2. It can be created under any folder in the project’s root folder. However, it is recommended to create controller classes in the Controllers folder as per the convention.
  3. Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.
  4. Return type of an action method can be any primitive or complex type. Learn more about it here.

Action Method Naming Conventions

As mentioned above, name of the action methods in the Web API controller plays an important role. Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above. However, you can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllNames(), GetStudents() or any other name which starts with Get.

The following table lists possible action method names for each HTTP method:

HTTP MethodPossible Web API Action Method NameUsage
GETGet()
get()
GET()
GetAllStudent()
*any name starting with Get *
Retrieves data.
POSTPost()
post()
POST()
PostNewStudent()
*any name starting with Post*
Inserts new record.
PUTPut()
put()
PUT()
PutStudent()
*any name starting with Put*
Updates existing record.
PATCHPatch()
patch()
PATCH()
PatchStudent()
*any name starting with Patch*
Updates record partially.
DELETEDelete()
delete()
DELETE()
DeleteStudent()
*any name starting with Delete*
Deletes record.

The following figure illustrates the overall request/response pipeline.

Web API Request Pipeline

Visit Web API HTTP Message Life Cycle Poster for more details.

Difference between Web API and MVC controller

Web API ControllerMVC Controller
Derives from System.Web.Http.ApiController classDerives from System.Web.Mvc.Controller class.
Method name must start with Http verbs otherwise apply http verbs attribute.Must apply appropriate Http verbs attribute.
Specialized in returning data.Specialized in rendering view.
Return data automatically formatted based on Accept-Type header attribute. Default to json or xml.Returns ActionResult or any derived type.
Requires .NET 4.0 or aboveRequires .NET 3.5 or above


Configure Web API

Web API supports code based configuration. It cannot be configured in web.config file. We can configure Web API to customize the behaviour of Web API hosting infrastructure and components such as routes, formatters, filters, DependencyResolver, MessageHandlers, ParamterBindingRules, properties, services etc.

We created a simple Web API project in the Create Web API Project section. Web API project includes default WebApiConfig class in the App_Start folder and also includes Global.asax as shown below.

Configure Web API

Global.asax

 Copy

public class WebAPIApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        
        //other configuration
    }
}

WebApiConfig

 Copy

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
 
        config.MapHttpAttributeRoutes();
 
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
 
        // configure additional webapi settings here..
    }
}

Web API configuration process starts when the application starts. It calls GlobalConfiguration.Configure(WebApiConfig.Register) in the Application_Start method. The Configure() method requires the callback method where Web API has been configured in code. By default this is the static WebApiConfig.Register() method.

As you can see above, WebApiConfig.Register() method includes a parameter of HttpConfiguration type which is then used to configure the Web API. The HttpConfiguration is the main class which includes following properties using which you can override the default behaviour of Web API.

PropertyDescription
DependencyResolverGets or sets the dependency resolver for dependency injection.
FiltersGets or sets the filters.
FormattersGets or sets the media-type formatters.
IncludeErrorDetailPolicyGets or sets a value indicating whether error details should be included in error messages.
MessageHandlersGets or sets the message handlers.
ParameterBindingRulesGets the collection of rules for how parameters should be bound.
PropertiesGets the properties associated with this Web API instance.
RoutesGets the collection of routes configured for the Web API.
ServicesGets the Web API services.

Web API Routing

In the previous section, we learned that Web API can be configured in WebApiConfig class. Here, we will learn how to configure Web API routes.

Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.

Web API supports two types of routing:

  1. Convention-based Routing
  2. Attribute Routing

Convention-based Routing

In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.

When we created Web API project using WebAPI template in the Create Web API Project section, it also added WebApiConfig class in the App_Start folder with default route as shown below.

Example: WebApiConfig with Default Route

 Copy

public static class WebApiConfig

{

    public static void Register(HttpConfiguration config)

    {

        // Enable attribute routing

        config.MapHttpAttributeRoutes();

        // Add default route using convention-based routing

        config.Routes.MapHttpRoute(

            name: “DefaultApi”,

            routeTemplate: “api/{controller}/{id}”,

            defaults: new { id = RouteParameter.Optional }

        );

    }

}

In the above WebApiConfig.Register() method, config.MapHttpAttributeRoutes() enables attribute routing which we will learn later in this section. The config.Routes is a route table or route collection of type HttpRouteCollection. The “DefaultApi” route is added in the route table using MapHttpRoute() extension method. The MapHttpRoute() extension method internally creates a new instance of IHttpRoute and adds it to an HttpRouteCollection. However, you can create a new route and add it into a collection manually as shown below.

Example: Add Default Route

 Copy

public static class WebApiConfig

{

    public static void Register(HttpConfiguration config)

    {

        config.MapHttpAttributeRoutes();

        // define route

        IHttpRoute defaultRoute = config.Routes.CreateRoute(“api/{controller}/{id}”,

                                            new { id = RouteParameter.Optional }, null);

        // Add route

        config.Routes.Add(“DefaultApi”, defaultRoute);

    }

}

The following table lists parameters of MapHttpRoute() method.

ParameterDescription
nameName of the route
routeTemplateURL pattern of the route
defaultsAn object parameter that includes default route values
constraintsRegex expression to specify characteristic of route values
handlerThe handler to which the request will be dispatched.

Now, let’s see how Web API handles an incoming http request and sends the response.

The following is a sample HTTP GET request.

Sample HTTP GET Request

GET http://localhost:1234/api/values/ HTTP/1.1

User-Agent: Fiddler

Host: localhost: 60464

Content-Type: application/json

Considering the DefaultApi route configured in the above WebApiConfig class, the above request will execute Get() action method of the ValuesController because HTTP method is a GET and URL is http://localhost:1234/api/values which matches with DefaultApi’s route template /api/{controller}/{id} where value of {controller} will be ValuesController. Default route has specified id as an optional parameter so if an id is not present in the url then {id} will be ignored. The request’s HTTP method is GET so it will execute Get() action method of ValueController.

If Web API framework does not find matched routes for an incoming request then it will send 404 error response.

The following figure illustrates Web API Routing.

Web API Routing

The following table displays which action method and controller will be executed on different incoming requests.

Request URLRequest HTTP MethodAction methodController
http://localhost:1234/api/courseGETGet()CourseController
http://localhost:1234/api/productPOSTPost()ProductController
http://localhost:1234/api/teacherPUTPut()TeacherController

 Note:

Web API also supports routing same as ASP.NET MVC by including action method name in the URL.

Configure Multiple Routes

We configured a single route above. However, you can configure multiple routes in the Web API using HttpConfiguration object. The following example demonstrates configuring multiple routes.

Example: Multiple Routes

 Copy

public static class WebApiConfig

{

                public static void Register(HttpConfiguration config)

    {

        config.MapHttpAttributeRoutes();

                // school route

        config.Routes.MapHttpRoute(

            name: “School”,

            routeTemplate: “api/myschool/{id}”,

            defaults: new { controller=”school”, id = RouteParameter.Optional }

            constraints: new { id =”/d+” }

        );

                // default route

        config.Routes.MapHttpRoute(

            name: “DefaultApi”,

            routeTemplate: “api/{controller}/{id}”,

            defaults: new { id = RouteParameter.Optional }

        );

    }

}

In the above example, School route is configured before DefaultApi route. So any incoming request will be matched with the School route first and if incoming request url does not match with it then only it will be matched with DefaultApi route. For example, request url is http://localhost:1234/api/myschool is matched with School route template, so it will be handled by SchoolController.

Parameter Binding in ASP.NET Web API

In the previous section, we learned how Web API route an HTTP request to a controller and action method. Here, we will learn how Web API binds HTTP request data to the parameters of an action method.

Action methods in Web API controllers can have one or more parameters of different types. It can be either primitive type or complex type. Web API binds action method parameters with the URL’s query string or with the request body depending on the parameter type.

By default, if the parameter type is of .NET primitive types such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from string type, then it sets the value of a parameter from the query string. And if the parameter type is the complex type, then Web API tries to get the value from the request body by default.

The following table lists the default rules for parameter binding.

HTTP MethodQuery StringRequest Body
GETPrimitive Type,
Complex Type
NA
POSTPrimitive TypeComplex Type
PUTPrimitive TypeComplex Type
PATCHPrimitive TypeComplex Type
DELETEPrimitive Type,
Complex Type
NA

Let’s see how Web API get values of action method parameters from the HTTP request.

Get Action Method with Primitive Parameter

Consider the following example of the GET action method that includes a single primitive type parameter.

Example: Primitive Parameter Binding

 Copy

public class StudentController : ApiController
{
    public Student Get(int id) 
    {
              
    }
}

As you can see, the above HTTP GET action method includes the id parameter of the int type. So, Web API will try to extract the value of id from the query string of the requested URL, convert it into int and assign it to the id parameter of the GET action method. For example, if an HTTP request is http://localhost/api/student?id=1 then the value of the id parameter will be 1.

The followings are valid HTTP GET Requests for the above action method.

http://localhost/api/student?id=1

http://localhost/api/student?ID=1

 Note:

Query string parameter name and action method parameter name must be the same (case-insensitive). If names do not match, then the values of the parameters will not be set. The order of the parameters can be different.

Multiple Primitive Parameters

Consider the following example of the GET action method with multiple primitive parameters.

Example: Multiple Parameters Binding

 Copy

public class StudentController : ApiController
{
    public Student Get(int id, string name) 
    {
 
    }
}

As you can see above, an HTTP GET method includes multiple primitive type parameters. So, Web API will try to extract the values from the query string of the requested URL. For example, if an HTTP request is http://localhost/api/student?id=1&name=steve, then the value of the id parameter will be 1, and the name parameter will be "steve".

Followings are valid HTTP GET Requests for the above action method.

http://localhost/api/student?id=1&name=steve

http://localhost/api/student?ID=1&NAME=steve

http://localhost/api/student?name=steve&id=1

 Note:

Query string parameter names must match with the name of an action method parameter. However, they can be in a different order.

POST Action Method with Primitive Parameter

An HTTP POST request is used to create a new resource. It can include request data into the HTTP request body and also in the query string.

Consider the following Post action method.

Example: Post Method with Primitive Parameter

 Copy

public class StudentController : ApiController
{
    public Student Post(id id, string name)
    {
           
    }
}

As you can see above, the Post() action method includes primitive type parameters id and name. So, by default, Web API will get values from the query string. For example, if an HTTP POST request is http://localhost/api/student?id=1&name=steve, then the value of the id parameter will be 1 and the name parameter will be "steve" in the above Post() method.

Now, consider the following Post() method with the complex type parameter.

Example: Post Method with Complex Type Parameter

 Copy

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
 
public class StudentController : ApiController
{
    public Student Post(Student stud)
    {
           
    }
}

The above Post() method includes the Student type parameter. So, as a default rule, Web API will try to get the values of the stud parameter from the HTTP request body.

Following is a valid HTTP POST request in the fiddler for the above action method.

Parameter Binding

Web API will extract the JSON object from the HTTP request body above, and convert it into a Student object automatically because the names of JSON object’s properties match with the name of the Student class properties (case-insensitive).

POST Method with Mixed Parameters

The HTTP Post action methods can include primitive and complex type parameters. Consider the following example.

Example: Post Method with Primitive and Complex Type Parameters

 Copy

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
 
public class StudentController : ApiController
{
    public Student Post(int age, Student student)
    {
 
    }
}

The above Post method includes both primitive and complex type parameters. So, by default , Web API will get the age parameter from query string and student parameter from the request body.

Following is a valid HTTP POST request in the fiddler for the above action method.

Parameter Binding

 Note:

Post action method cannot include multiple complex type parameters because, at most, one parameter is allowed to be read from the request body.

Parameter binding for Put and Patch method will be the same as the POST method in Web API.

[FromUri] and [FromBody]

You have seen that by default, ASP.NET Web API gets the value of a primitive parameter from the query string and a complex type parameter from the request body. But, what if we want to change this default behavior?

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.

For example, consider the following GET method.

Example: FormUri

 Copy

public class StudentController : ApiController
{
    public Student Get([FromUri] Student stud)
    {
 
    }
}

In the above example, the Get() method includes a complex type parameter with the [FromUri] attribute. So, Web API will try to get the value of the Student type parameter from the query string. For example, if an HTTP GET request http://localhost:xxxx/api/student?id=1&name=steve then Web API will create an object the Student type and set its id and name property values to the value of id and name query string parameter.

 Note:

The name of the complex type’s properties and the query string parameters must match.

Action Method Return Type

In the previous section, you learned about parameter binding with Web API action method. Here, you will learn about the return types of action methods which in turn will be embedded in the Web API response sent to the client.

The Web API action method can have following return types.

  1. Void
  2. Primitive type or Complex type
  3. HttpResponseMessage
  4. IHttpActionResult

Void

It’s not necessary that all action methods must return something. It can have void return type.

For example, consider the following Delete action method that just deletes the student from the data source and returns nothing.

Example: Void Return Type

 Copy

public class StudentController : ApiController

{

    public void Delete(int id)

    {

        DeleteStudentFromDB(id);

    }

}

As you can see above Delete action method returns void. It will send 204 “No Content” status code as a response when you send HTTP DELETE request as shown below.

Void Response Status

Primitive or Complex Type

An action method can return primitive or other custom complex types as other normal methods.

Consider the following Get action methods.

Example: Primitive or Complex Return Type

 Copy

public class Student

{

    public int Id { get; set; }

    public string Name { get; set; }

}

public class StudentController : ApiController

{

    public int GetId(string name)

    {

        int id = GetStudentId(name);

        return id;

    }

    public Student GetStudent(int id)

    {

        var student = GetStudentFromDB(id);

        return student;

    }

}

As you can see above, GetId action method returns an integer and GetStudent action method returns a Student type.

An HTTP GET request http://localhost:xxxx/api/student?name=john will return following response in Fiddler.

Primitive Return Type in Response

An HTTP GET request http://localhost:xxxx/api/student?id=1 will return following response in Fiddler.

Complex Return Type in Response

HttpResponseMessage

Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API request/response pipeline.

Web API Request Pipeline

Visit Web API HTTP Message Life Cycle Poster for more details.

As you can see in the above figure, the Web API controller returns HttpResponseMessage object. You can also create and return an object of HttpResponseMessage directly from an action method.

The advantage of sending HttpResponseMessage from an action method is that you can configure a response your way. You can set the status code, content or error message (if any) as per your requirement.

Example: Return HttpResponseMessage

 Copy

public HttpResponseMessage Get(int id)

{

    Student stud = GetStudentFromDB(id);

    if (stud == null) {

        return Request.CreateResponse(HttpStatusCode.NotFound, id);

    }

    return Request.CreateResponse(HttpStatusCode.OK, stud);

In the above action method, if there is no student with specified id in the DB then it will return HTTP 404 Not Found status code, otherwise it will return 200 OK status with student data.

For example, an http GET request http://localhost:xxxx/api/student?id=100 will get following response considering student with id=100 does not exists in the DB.

Web API Response in Fiddler

The same way, an HTTP GET request http://localhost:60464/api/student?id=1 will get following response considering student with id=1 exists in the database .

Web API Response in Fiddler

IHttpActionResult

The IHttpActionResult was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.

You can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.

Example: Return IHttpActionResult Type using Ok() and NotFound() Methods

 Copy

public IHttpActionResult Get(int id)

{

    Student stud = GetStudentFromDB(id);

    if (stud == null)

    {

        return NotFound();

    }

    return Ok(stud);

}

In the above example, if student with specified id does not exists in the database then it will return response with the status code 404 otherwise it sends student data with status code 200 as a response. As you can see, we don’t have to write much code because NotFound() and Ok() method does it all for us.

The following table lists all the methods of ApiController class that returns an object of a class that implements IHttpActionResult interface.

ApiController MethodDescription
BadRequest()Creates a BadRequestResult object with status code 400.
Conflict()Creates a ConflictResult object with status code 409.
Content()Creates a NegotiatedContentResult with the specified status code and data.
Created()Creates a CreatedNegotiatedContentResult with status code 201 Created.
CreatedAtRoute()Creates a CreatedAtRouteNegotiatedContentResult with status code 201 created.
InternalServerError()Creates an InternalServerErrorResult with status code 500 Internal server error.
NotFound()Creates a NotFoundResult with status code404.
Ok()Creates an OkResult with status code 200.
Redirect()Creates a RedirectResult with status code 302.
RedirectToRoute()Creates a RedirectToRouteResult with status code 302.
ResponseMessage()Creates a ResponseMessageResult with the specified HttpResponseMessage.
StatusCode()Creates a StatusCodeResult with the specified http status code.
Unauthorized()Creates an UnauthorizedResult with status code 401.

Visit MSDN to know all the members of ApiController.

Create Custom Result Type

You can create your own custom class as a result type that implements IHttpActionResult interface.

The following example demonstrates implementing IHttpActionResult class.

Example: Create Custom Result Type

 Copy

public class TextResult : IHttpActionResult

{

    string _value;

    HttpRequestMessage _request;

    public TextResult(string value, HttpRequestMessage request)

    {

        _value = value;

        _request = request;

    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)

    {

        var response = new HttpResponseMessage()

        {

            Content = new StringContent(_value),

            RequestMessage = _request

        };

        return Task.FromResult(response);

    }

}

Now, you can return TextResult object from the action method as shown below.

Example: Return Custom Result Type

 Copy

public IHttpActionResult GetName(int id)

{

    string name = GetStudentName(id);

    if (String.IsNullOrEmpty(name))

    {

        return NotFound();

    }

    return new TextResult(name, Request);

}

Web API Request/Response Data Formats

Here, you will learn how Web API handles different formats of request and response data.

Media Type

Media type (aka MIME type) specifies the format of the data as type/subtype e.g. text/html, text/xml, application/json, image/jpeg etc.

In HTTP request, MIME type is specified in the request header using Accept and Content-Type attribute. The Accept header attribute specifies the format of response data which the client expects and the Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.

For example, if a client wants response data in JSON format then it will send following GET HTTP request with Accept header to the Web API.

HTTP GET Request:

GET http://localhost:60464/api/student HTTP/1.1
User-Agent: Fiddler
Host: localhost:1234
Accept: application/json

The same way, if a client includes JSON data in the request body to send it to the receiver then it will send following POST HTTP request with Content-Type header with JSON data in the body.

HTTP POST Request:

POST http://localhost:60464/api/student?age=15 HTTP/1.1
User-Agent: Fiddler
Host: localhost:60464
Content-Type: application/json
Content-Length: 13
 
{
  id:1,
  name:'Steve'
}

Web API converts request data into CLR object and also serialize CLR object into response data based on Accept and Content-Type headers. Web API includes built-in support for JSON, XML, BSON, and form-urlencoded data. It means it automatically converts request/response data into these formats OOB (out-of the box).

Example: Post Action Method

 Copy

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
 
public class StudentController : ApiController
{
    public Student Post(Student student)
    {
        // save student into db
        var insertedStudent = SaveStudent(student);
 
        return insertedStudent;
    }
}

As you can see above, the Post() action method accepts Student type parameter, saves that student into DB and returns inserted student with generated id. The above Web API handles HTTP POST request with JSON or XML data and parses it to a Student object based on Content-Type header value and the same way it converts insertedStudent object into JSON or XML based on Accept header value.

The following figure illustrates HTTP POST request in fiddler.

Request-Response Data Format

In the above figure, Accept header specifies that it expects response data in XML format and Content-Type specifies that the student data into request body is in the JSON format. The following is the response upon execution of the above request.

Request-Response Data Format

The same way, you can specify different request & response format using accept and content-type headers and Web API will handle them without any additional changes.

The following HTTP POST request sends data in XML format and receives data in JSON format.

Web API Request

The above HTTP POST request will get the following response upon execution.

Web API Response

Thus, Web API handles JSON and XML data by default. Learn how Web API formats request/response data using formatters in the next section.

ASP.NET Web API: Media-Type Formatters

As you have seen in the previous section that Web API handles JSON and XML formats based on Accept and Content-Type headers. But, how does it handle these different formats? The answer is: By using Media-Type formatters.

Media type formatters are classes responsible for serializing request/response data so that Web API can understand the request data format and send data in the format which client expects.

Web API includes following built-in media type formatters.

Media Type Formatter ClassMIME TypeDescription
JsonMediaTypeFormatterapplication/json, text/jsonHandles JSON format
XmlMediaTypeFormatterapplication/xml, text/jsonHandles XML format
FormUrlEncodedMediaTypeFormatterapplication/x-www-form-urlencodedHandles HTML form URL-encoded data
JQueryMvcFormUrlEncodedFormatterapplication/x-www-form-urlencodedHandles model-bound HTML form URL-encoded data

Retrieve Built-in Media Type Formatters

As mentioned Web API includes above listed media type formatter classes by default. However, you can also add, remove or change the order of formatters.

The following example demonstrates HTTP Get method that returns all built-in formatter classes.

Example: Retrieve Built-in Formatters in C#

 Copy

public class FormattersController : ApiController
{
    public IEnumerable<string> Get()
    {
        IList<string> formatters = new List<string>();
 
        foreach (var item in GlobalConfiguration.Configuration.Formatters)
        {
            formatters.Add(item.ToString());
        }
 
        return formatters.AsEnumerable<string>();
    }
}

In the above example, GlobalConfiguration.Configuration.Formatters returns MediaTypeFormatterCollection that includes all the formatter classes. The above example returns names of all the formatter classes as shown below.

Built-in Media-Type Formatters

Alternatively, MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example demonstrates retrieving media type formatters using MediaTypeFormatterCollection’s properties.

Example: Retrieve Built-in Formatters in C#

 Copy

public class FormattersController : ApiController
{
    public IEnumerable<string> Get()
    {
        IList<string> formatters = new List<string>();
 
        formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter.GetType().FullName);
        formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter.GetType().FullName);
        formatters.Add(GlobalConfiguration.Configuration.Formatters.FormUrlEncodedFormatter.GetType().FullName);
        
        return formatters.AsEnumerable<string>();
    }
}

The above example returns following response to the browser.

Media-Type Formatters

BSON Formatter

Web API also supports BSON format. As the name suggests, BSON is binary JSON, it is a binary-encoded serialization of JSON-like documents. Currently there is very little support for BSON and no JavaScript implementation is available for clients running in browsers. This means that it is not possible to retrieve and automatically parse BSON data to JavaScript objects.

Web API includes built-in formatter class BsonMediaTypeFormatter for BSON but it is disabled by default. Learn more about BSON support in Web API here.

JSON Formatter

As mentioned above, Web API includes JsonMediaTypeFormatter class that handles JSON format. The JsonMediaTypeFormatter converts JSON data in an HTTP request into CLR objects (object in C# or VB.NET) and also converts CLR objects into JSON format that is embeded within HTTP response.

Internally, JsonMediaTypeFormatter uses third-party open source library called Json.NET to perform serialization.

Configure JSON Serialization

JSON formatter can be configured in WebApiConfig class. The JsonMediaTypeFormatter class includes various properties and methods using which you can customize JSON serialization. For example, Web API writes JSON property names with PascalCase by default. To write JSON property names with camelCase, set the CamelCasePropertyNamesContractResolver on the serializer settings as shown below.

Example: Customize JSON Serialization in C#

 Copy

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
            
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
 
        // configure json formatter
        JsonMediaTypeFormatter jsonFormatter = config.Formatters.JsonFormatter;
 
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

XML Formatter

The XmlMediaTypeFormatter class is responsible for serializing model objects into XML data. It uses System.Runtime.DataContractSerializer class to generate XML data.

Web API Filters

Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.

Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.

The following table lists important interfaces and classes that can be used to create Web API filters.

Filter TypeInterfaceClassDescription
Simple FilterIFilterDefines the methods that are used in a filter
Action FilterIActionFilterActionFilterAttributeUsed to add extra logic before or after action methods execute.
Authentication FilterIAuthenticationFilterUsed to force users or clients to be authenticated before action methods execute.
Authorization FilterIAuthorizationFilterAuthorizationFilterAttributeUsed to restrict access to action methods to specific users or groups.
Exception FilterIExceptionFilterExceptionFilterAttributeUsed to handle all unhandled exception in Web API.
Override FilterIOverrideFilterUsed to customize the behaviour of other filter for individual action method.

As you can see, the above table includes class as well as interface for some of the filter types. Interfaces include methods that must be implemented in your custom attribute class whereas filter class has already implemented necessary interfaces and provides virtual methods, so that they can be overridden to add extra logic. For example, ActionFilterAttribute class includes methods that can be overridden. We just need to override methods which we are interested in, whereas if you use IActionFilter attribute than you must implement all the methods.

Visit MSDN to know all the classes and interfaces available in System.Web.Http.Filters.

Let’s create simple LogAttribute class for logging purpose to demonstrate action filter.

First, create a LogAttribute class derived from ActionFilterAttribute class as shown below.

Example: Web API Filter Class

 Copy

public class LogAttribute : ActionFilterAttribute 
 {
    public LogAttribute()
    {
 
    }
 
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
 
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
}

In the above example, LogAttribute is derived from ActionFilterAttribute class and overrided OnActionExecuting and OnActionExecuted methods to log in the trace listeners. (You can use your own logging class to log in textfile or other medium.)

Another way of creating LogAttribute class is by implementing IActionFilter interface and deriving Attribute class as shown below.

Example: Web API Filter Class

 Copy

public class LogAttribute : Attribute, IActionFilter
{
    public LogAttribute()
    {
 
    }
 
    public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
 
        var result = continuation();
 
        result.Wait();
            
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
 
        return result;
    }
 
    public bool AllowMultiple
    {
        get { return true; }
    }
} 

In the above example, deriving from Attribute class makes it an attribute and implementing IActionFilter makes LogAttribute class as action filter. So now, you can apply [Log] attributes on controllers or action methods as shown below.

Example: Apply Web API Filter on Controller

 Copy

[Log]
public class StudentController : ApiController
{
    public StudentController()
    {
            
    }
 
    public Student Get()
    {
        //provide implementation  
    }
}

So now, it will log all the requests handled by above StudentController. Thus you can create filters for cross-cutting concerns.

Consume Web API in .NET using HttpClient

The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol. However, WebClient class had some limitations. The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient. Here, we will use HttpClient class in console application to send data to and receive data from Web API which is hosted on local IIS web server. You may use HttpClient in other .NET applications also such as MVC Web Application, windows form application, windows service application etc.

Let’s see how to consume Web API using HttpClient in the console application.

We will consume the following Web API created in the previous section.

Example: Web API Controller

 Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
 
namespace MyWebAPI.Controller
{
    public class StudentController : ApiController
    {
        public IHttpActionResult GetAllStudents(bool includeAddress = false)
        {
            IList<StudentViewModel> students = null;
 
            using (var ctx = new SchoolDBEntities())
            {
                students = ctx.Students.Include("StudentAddress").Select(s => new StudentViewModel()
                {
                    Id = s.StudentID,
                    FirstName = s.FirstName,
                    LastName = s.LastName,
                    Address = s.StudentAddress == null || includeAddress == false ? null : new AddressViewModel()
                    {
                        StudentId = s.StudentAddress.StudentID,
                        Address1 = s.StudentAddress.Address1,
                        Address2 = s.StudentAddress.Address2,
                        City = s.StudentAddress.City,
                        State = s.StudentAddress.State
                    }
                }).ToList<StudentViewModel>();
            }
 
            if (students.Count == 0)
            {
                return NotFound();
            }
 
            return Ok(students);
        }
 
        public IHttpActionResult PostNewStudent(StudentViewModel student)
        {
            if (!ModelState.IsValid)
                return BadRequest("Not a valid data");
 
            using (var ctx = new SchoolDBEntities())
            {
                ctx.Students.Add(new Student()
                {
                    StudentID = student.Id,
                    FirstName = student.FirstName,
                    LastName = student.LastName
                });
 
                ctx.SaveChanges();
            }
            return Ok();
        }
 
        public IHttpActionResult Put(StudentViewModel student)
        {
            if (!ModelState.IsValid)
                return BadRequest("Not a valid data");
 
            using (var ctx = new SchoolDBEntities())
            {
                var existingStudent = ctx.Students.Where(s => s.StudentID == student.Id).FirstOrDefault<Student>();
 
                if (existingStudent != null)
                {
                    existingStudent.FirstName = student.FirstName;
                    existingStudent.LastName = student.LastName;
 
                    ctx.SaveChanges();
                }
                else
                {
                    return NotFound();
                }
            }
            return Ok();
        }
 
 
        public IHttpActionResult Delete(int id)
        {
            if (id <= 0)
                return BadRequest("Not a valid studet id");
 
            using (var ctx = new SchoolDBEntities())
            {
                var student = ctx.Students
                    .Where(s => s.StudentID == id)
                    .FirstOrDefault();
 
                ctx.Entry(student).State = System.Data.Entity.EntityState.Deleted;
                ctx.SaveChanges();
            }
            return Ok();
        }
    }
}

Step 1:

First, create a console application in Visual Studio 2013 for Desktop.

Step 2:

Open NuGet Package Manager console from TOOLS -> NuGet Package Manager -> Package Manager Console and execute following command.

Install-Package Microsoft.AspNet.WebApi.Client

Step 3:

Now, create a Student model class because we will send and receive Student object to our Web API.

Example: Model Class

 Copy

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Send GET Request

The following example sends an HTTP GET request to Student Web API and displays the result in the console.

Example: Send HTTP GET Request using HttpClient

 Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
 
namespace HttpClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:60464/api/");
                //HTTP GET
                var responseTask = client.GetAsync("student");
                responseTask.Wait();
 
                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
 
                    var readTask = result.Content.ReadAsAsync<Student[]>();
                    readTask.Wait();
 
                    var students = readTask.Result;
 
                    foreach (var student in students)
                    {
                        Console.WriteLine(student.Name);
                    }
                }
            }
            Console.ReadLine();
        }        
    }
}

Let’s understand the above example step by step.

First, we have created an object of HttpClient and assigned the base address of our Web API. The GetAsync() method sends an http GET request to the specified url. The GetAsync() method is asynchronous and returns a Task. Task.wait() suspends the execution until GetAsync() method completes the execution and returns a result.

Once the execution completes, we get the result from Task using Task.result which is HttpResponseMessage. Now, you can check the status of an http response using IsSuccessStatusCode. Read the content of the result using ReadAsAsync() method.

Thus, you can send http GET request using HttpClient object and process the result.

Send POST Request

Similarly, you can send HTTP POST request using PostAsAsync() method of HttpClient and process the result the same way as GET request.

The following example send http POST request to our Web API. It posts Student object as json and gets the response.

Example: Send HTTP POST Request using HttpClient

 Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
 
namespace HttpClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var student = new Student() { Name = "Steve" };
 
            var postTask = client.PostAsJsonAsync<Student>("student", student);
            postTask.Wait();
 
            var result = postTask.Result;
            if (result.IsSuccessStatusCode)
            {
 
                var readTask = result.Content.ReadAsAsync<Student>();
                readTask.Wait();
 
                var insertedStudent = readTask.Result;
 
                Console.WriteLine("Student {0} inserted with id: {1}", insertedStudent.Name, insertedStudent.Id);
            }
            else
            {
                Console.WriteLine(result.StatusCode);
            }
        }
    }
}

The following table lists all the methods of HttpClient to send different HTTP requests.

Method NameDescription
GetAsyncSends a GET request to the specified Uri as an asynchronous operation.
GetByteArrayAsyncSends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation.
GetStreamAsyncSends a GET request to the specified Uri and returns the response body as a stream in an asynchronous operation.
GetStringAsyncSends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation.
PostAsyncSends a POST request to the specified Uri as an asynchronous operation.
PostAsJsonAsyncSends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
PostAsXmlAsyncSends a POST request as an asynchronous operation to the specified Uri with the given value serialized as XML.
PutAsyncSends a PUT request to the specified Uri as an asynchronous operation.
PutAsJsonAsyncSends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
PutAsXmlAsyncSends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as XML.
DeleteAsyncSends a DELETE request to the specified Uri as an asynchronous operation.

Configure Dependency Injection with Web API

Here you will learn how to configure and use IoC container for dependency injection with Web API.

There are many IoC containers available for dependency injection such as Ninject, Unity, castleWidsor, structuremap etc. Here we will use Ninject for dependency injection.

The following is our sample Web API that uses instance of a class that implements IRepository.

Example: Simple Web API Controller

 Copy

public class StudentController : ApiController
{
    private IRepository _repo = null;
 
    public StudentController(IRepository repo)
    {
        _repo = repo;
    }
 
    public IList<Student> Get()
    {
        return  _repo.GetAll();
    }
}

The following are IRepository and StudentRepository class.

Example: Repository

 Copy

public interface IRepository
{
    IList<Student> GetAll();
}
 
public class StudentRepository : IRepository
{
    public IList<Student> GetAll()
    {
        //return students from db here
    }
}

Now, let’s use Ninject which will inject StudentRepository class in StudentController.

First of all, you need to install Ninject library for Web API using NuGet. To do this, right click on your project in the solution explorer -> click on Manage NuGet packages... This will open NuGet popup. Now search for webapicontrib in the search box as shown below.

Web API Configuration

As you can see, this will list all the IoC containers for Web API. Select WebApiContrib.IoC.Ninject and click Install.

Web API Configuration

Now, you need to install Ninject.Extensions.ChildKernel. Search for it and install it.

Web API Configuration

So now after installing necessary packages for Ninject, we need to configure it.

In order to use dependency injection with Web API, we need to create a resolver class that implements IDependencyResolver interface. Here, we have created NinjectResolver class in Infrastructure folder in our Web API project as shown below.

Example: DI Resolver

 Copy

public class NinjectResolver : IDependencyResolver
{
    private IKernel kernel;
 
    public NinjectResolver() : this(new StandardKernel()) 
    { 
    }
 
    public NinjectResolver(IKernel ninjectKernel, bool scope = false)
    {
        kernel = ninjectKernel;
        if (!scope)
        {
            AddBindings(kernel);
        }
    }
 
    public IDependencyScope BeginScope()
    {
        return new NinjectResolver(AddRequestBindings(new ChildKernel(kernel)), true);
    }
 
    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }
 
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }
 
    public void Dispose()
    {
            
    }
 
    private void AddBindings(IKernel kernel)
    {
        // singleton and transient bindings go here
    }
 
    private IKernel AddRequestBindings(IKernel kernel)
    {
        kernel.Bind<IRepository>().To<StudentRepository>().InSingletonScope();
        return kernel;
    }
}

Now, we need to configure NijectResolver with Web API in the WebApiConfig class as shown below.

Example: Set DI Resolver

 Copy

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.DependencyResolver = new NinjectResolver();
 
        config.MapHttpAttributeRoutes();
 
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
 
    }
}

As you can see above, HttpConfiguration.DependencyResolver is set to NinjectResolver. So now, Web API will use NinjectResolver class to create the objects it needs.

Thus, you can configure IoC container with Web API.

Web API Hosting

In this section, you will learn how to host a Web API.

The Web API application can be hosted in two ways.

  • IIS Hosting
  • Self Hosting

IIS Hosting

Web API can be hosted under IIS, in the same way as a web application. You have learned to create a Web API in the previous section. As you have seen there, a Web API is created with ASP.NET MVC project by default. So, when you host your MVC web application under IIS it will also host Web API that uses the same base address.

Self Hosting

You can host a Web API as separate process than ASP.NET. It means you can host a Web API in console application or windows service or OWIN or any other process that is managed by .NET framework.

You need to do following steps in order to self-host a web API.

  1. Use HttpConfiguration to configure a Web API
  2. Create HttpServer and start listening to incoming http requests

Let’s see how to host a simple Web API in console application.

First of all, create a console project in Visual Studio 2012 for Desktop (or latter version).

Note: You must open Visual Studio in Administration mode.

Create Console Application

Now, you need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet. Right click on project in the Solution Explorer window and select Manage NuGet Packges..

Open NuGet Manager

In the Manage NuGet Packages window, select Online option in left pan and search for web-api. This will list all the packages for Web API. Now, look for Microsoft ASP.NET Web API 2.2 Self Host package and click Install.

Install Web API Self Host Package

Click on Accept button in the License Acceptance window.

Accept License Agreement

This will install the package into your project.

Install Web API self Hosting Package

Now write the following code in the Main() method of Program class.

Example: Self-Hosting Web API

 Copy

class Program

{

    static void Main(string[] args)

    {

        var config = new HttpSelfHostConfiguration(“http://localhost:1234”);

        var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());

        var task = server.OpenAsync();

        task.Wait();

        Console.WriteLine(“Web API Server has started at http://localhost:1234”);

        Console.ReadLine();

    }

}

In the above code, first we created an object of HttpSelfHostConfiguration class by passing uri location. Then, we created an object of HttpSelfHostServer by passing config and HttpMessageHandler object. And then we started listening for incoming request by calling server.OpenAsync() method. This will listen requests asynchronously, so it will return Task object.

Create MyWebAPIMessageHandler class and write the following code.

Example: MessageHandler

 Copy

class MyWebAPIMessageHandler : HttpMessageHandler

{

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

    {

        var task = new Task<HttpResponseMessage>(() => {

            var resMsg = new HttpResponseMessage();

            resMsg.Content = new StringContent(“Hello World!”);

            return resMsg;

        });

        task.Start();

        return task;

    }

}

Thus, you can create simple console application and host simple Web API that returns “Hello World!” to every request.

Run the console application using Ctrl + F5.

Run Console Application

Open web browser and enter http://localhost:1234/ and see the result.

Response in Browser

Hosting Controller Infrastructure

You can use the same ASP.NET routing and ApiController capabilities of ASP.NET Hosting in self hosting.

In the same self hosting console application, create simple HomeController class as shown below.

Example: Web API Controller

 Copy

public class HomeController : ApiController

{

    public string Get() {

        return “Hello World!”;

    }

    public string Get(string name) {

        return “Hello ” + name;

    }

}

Now, in the Main() method, configure a default route using config object as shown below.

Example: Self Hosting Web API

 Copy

static void Main(string[] args)

{

    var config = new HttpSelfHostConfiguration(“http://localhost:1234”);

    config.Routes.MapHttpRoute(“default”,

                                “api/{controller}/{id}”,

                                new { controller = “Home”, id = RouteParameter.Optional });

    var server = new HttpSelfHostServer(config);           

    var task = server.OpenAsync();

    task.Wait();

    Console.WriteLine(“Web API Server has started at http://localhost:1234”);

    Console.ReadLine();

}

Please notice that we removed an object of MessageHandler when creating an object of HttpSelfHostServer.

Now, run the console application by pressing Ctrl + F5. Open the browser and enter http://localhost:1234/api or http://localhost:1234/api?name=steve and see the result as shown below.

Web API Interview Questions

1. What is ASP.Net Web API?

A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP-based services. Clients dealing with mobile applications and web browsers can consume Web API.

2. What are the differences between Web API and WCF REST API?

A: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message queues, one-way messaging, and duplex communication. WEB API supports any media format, even XML and JSON, while WCF supports SOAP and XML formats. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for developing service-oriented applications. To run Web API, there is no configuration required, while in the case of WCF, a lot of configuration is required to run it.

3. What are the advantages of using ASP.Net Web API?

A: The advantages of using ASP.Net Web API are mentioned below:

  • It completes support for routing
  • Is works as HTTP using standard HTTP verbs such as GET, DELETE, POST, PUT, to name a few, for all CRUD operations
  • It can be hosted in IIS as well as self-host outside of IIS
  • It supports OData
  • It supports validation and model binding
  • The response is generated in XML or JSON format by using MediaTypeFormatter

4. What are the several return types in ASP.Net Web API?

A: The various return types in ASP.Net Web API are:

  • IHttpActionResult
  • HttpResponseMessage
  • Void
  • Other Type – string, int, or other entity types.

5. What is ASP.Net Web API routing?

A: It is the process that determines the action and controller that should be called.

The ways to incorporate routing in Web API include:

  • Attribute based routing
  • Convention based routing

6. What are Media type formatters in Web API?

A: The Media type formatter in Web API include:

  • MediaTypeFormatter – It is the base class that helps to handle serializing and deserializing strongly-typed objects.
  • BefferedMediaTypeFormatter – It signifies a helper class to allow asynchronous formatter on top of the asynchronous formatter infrastructure.

7. What is the CORS issue in Web API?

A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin restriction for JavaScript. Same-origin means JavaScript only makes AAJAX call for web pages within the same-origin.

You have to install the CORS nuget package by using Package Manager Console to enable CORS in Web API.

Open WebAPIConfig.cs file

add config.EnableCors();

Add EnableCors attribute to the Controller class and define the origin.

[EnableCors(origins: “”, headers: “*”, methods: “*”)].

8. How to secure an ASP.Net Web API?

A: To secure an ASP.Net Web API, we need to control the Web API and decide who can access the API and who cannot access it. Web API can be accessed by anyone who knows about the URL.

9. What are the differences between HTTP Get and HTTP Post?

A: GET and POST are two important verbs of HTTP.

  • Parameters of GET are included in the URL; while parameters of POST are included in the body
  • GET requests do not make any changes to the server; while POST does make changes to the server
  • A GET request is idempotent; while a POST request is non-idempotent
  • In a GET request, data is sent in plain text; binary and text data are sent

10. How can Web API be used?

A: Web API can easily be used with ASP.Net Forms. You can add Web API Controller and route in Application Start method in Global.asax file.

11.Exception filters in ASP.Net Web API

A: Exception filters in Web API help in implementing IExceptionFilters interface. They perform when an action throws an exception at any point.

12. Do we return Views from ASP.Net Web API?

A: No, it is not possible as Web API creates an HTTP-based service. It is mostly available in the MVC application.

13. What is new in ASP.Net Web API 2.0?

A: The features introduced in ASP.NET Web API framework v2.0 are:

  • Attribute Routing
  • External Authentication
  • CORS (Cross-Origin Resource Sharing)
  • OWIN (Open Web Interface for .NET) Self Hosting
  • IHttpActionResult
  • Web API Odata

14. How do we limit access to methods with an HTTP verb in Web API?

A: An attribute has to be added as shown below:

[HttpGet]

public HttpResponseMessage Test()

{

HttpResponseMessage response = new HttpResponseMessage();

///

return response;

}

[HttpPost]

public void Save([FromBody]string value)

{

}

15. How do we make sure that Web API returns data in JSON format only?

A: To ensure that web API returns data in JSON format only, open “WebApiConfig.cs” file as well as add the below line:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/json”))

To learn JSON format, you can also take up free online courses that will help you enhance your basic skills about the same.

16. How to provide Alias name for an action method in Web API?

A: By adding an attribute ActionName, an Alias name can be provided:

[ActionName(“InertUserData”)]

// POST api/

public void Post([FromBody]string value)

{

}

17. How can we handle errors in Web API?

A: Handling errors or exceptions in Web API can be done with the help of the following classes –

  • Using HttpResponseException –This exception class helps to return the HTTP status code specified in the exception Constructor.
  • Using HttpError – This exception class helps to return meaningful error code to the client as HttpResponseMessage.
  • Using Exception filters – Exception filters help in catching unhandled exceptions or errors generated in Web API and they can be used whenever the controller action method throws the unhandled error. 

18. How to host Web API?

A: There are two ways how Web API application can be hosted:

  • Self Hosting 
  • IIS Hosting 

19. How to consume Web API using HTTPClient?

A: HTTPClient is introduced in HTTPClient class for communicating with ASP.Net Web API. This HTTPClient class is used either in a console application or in an MVC application.

20. Explain oData with ASP.Net Web API. 

A: OData is the acronym for Open Data Protocol. It is a Rest-based data access protocol. OData provides a way to manipulate data by making use of CRUD operations. ASP.Net Web API supports OData V3 and V4.

To use OData in ASP.Net Web API, you would need an OData package. You have to run the below command in the Package Manager Console.

Install-Package Microsoft.AspNet.Odata

21. Can we consume Web API 2 in C# console application?

A: Yes, Web API 2 can be consumed in Console Application, MVC, Angular JS, or any other application.

22. Perform Web API 2 CRUD operation using Entity Framework.

A: CRUD operation can be performed by using entity framework with Web API.

23. How to enable HTTPs in Web API?

A: ASP.Net Web API runs over HTTP protocol. You can create a class and get a class with AuthorizationFilterAttribute. Now check if the requested URL has HTTPs.

24. How to implement Basic Authentication in ASP.Net Web API?

A: Basic Authentication in ASP.Net Web API can be implemented where the client sends a request with an Authorization header and the word Basic. In Basic Authentication, the Authorization header contains the word Basic followed by a base 64 encoded string.

The syntax for Basic Authentication –

1Authorization: Basic username: password

25. What is Token Based Authentication in Web API?

A: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-based approach.

26. What is content negotiation in .Net Web API?

A: In ASP.Net Web API, content negotiation is done on the server side. This helps in determining the media type formatter, especially when it is about returning the response to an incoming request.

27. What is ASP.Net identity?

A: ASP.Net identity is the membership management framework that Microsoft provides. It is very easily incorporated with Web API. This can help you to build a secure HTTP service.

28. What is Bearer Authentication in .Net Web API?

A: Bearer authentication is also known as Token-based authentication.

29. What is REST?

A: REST stands for Representational State Transfer. This is an architectural pattern that helps in exchanging data over a disseminated environment.

REST architectural pattern treats all the services as resources and a client can access these resources by using HTTP protocol methods which include PUT, GET, POST, and DELETE.

30. What is Not REST?

A: The mentioned below are not REST:

  • A standard
  • A protocol
  • 3. A replacement of SOAP

31. What are the differences between REST and SOAP?

A: Here are some differences between REST and SOAP:

SOAPREST
SOAP stands for Simple Object Access ProtocolREST stands for Representational State Transfer.
SOAP is a protocol, called an XMLREST is not a protocol but you can call it an architectural pattern example which is used for resource-based architecture.
SOAP specifies both stateless as well as state-full implementationREST is completely stateless.
SOAP applies message formats like XML;REST does not apply message formats like XML or JSON.
To expose the service, SOAP uses interfaces and named operations;REST uses URI and methods like POST, GET, PUT, and DELETE for exposing resources (service).

32. What are the differences between ASP.NET MVC and ASP.NET Web API?

A: MVC is used to create web applications that can return views as well as data, while ASP.NET Web API is used to create restful HTTP services simply, which returns only data and no view. In MVC, the request is mapped to the actions name, while the request is mapped to the actions based on HTTP verbs in Web API.

33. Is it true that ASP.NET Web API has replaced WCF?

A: It is not true! It is rather just another way to build non-SOAP-based services like plain XML or JSON strings. It comes with additional advantages such as using HTTP’s full features and reaching more clients such as mobile devices, etc.

34. Explain media Formatters in Web API 2

A: These are classes that are responsible for response data. The Web API understands the request data format as well as sends data in the format as expected by the clients.

35. Which protocol is supported by Web API?

A:  The only protocol supported by Web API is HTTP. Therefore, it can be consumed by a  client that supports HTTP protocol.

36. What are the similarities between MVC and Web API?

A: Both MVC and Web API are based on the principle of Separation of concerns and concepts like controllers, routing, and models.

37. What are the differences between MVC and Web API?

A: MVC is used for developing applications that come with User interfaces. The Views in MVC are used to develop a User Interface. Web API is used for developing HTTP services. To fetch data, the Web API methods are called by other applications.

38. Who can consume Web API?

A: Web API is consumed by a client that supports HTTP verbs such as DELETE, GET, PUT, and POST. They can quite easily be consumed by a client as Web API services do not need any configuration. Web API can be consumed very easily by portable devices.

39. How are Requests mapped to Action methods in Web API?

A: As Web API uses HTTP verbs, a client that can consume a Web API that needs ways to call the Web API method. A client can use the HTTP verbs to call the action methods of the Web API.

Take a look at the example given below. In order to call a method like GetEmployee, client can use a jQuery method like:

$.get(“/api/Employees/1”, null, function(response)

{

$(“#employees”).html(response);

});

Therefore, the method name above has no mention. As an alternative, GetEmployee method can be called by using the GET HTTP verb.

The GetEmployee method can be defined as:

 [HttpGet]

 public void GetEmployee(int id)

 {

StudentRepository.Get(id);

 }

As the GetEmployee method can be seen decorated with the [HttpGet] attribute, different verbs to map the different HTTP requests have to be used:

  • HttpGet
  • HttpPut 
  • HttpPost
  • HttpDelete

40. Can the HTTP request be mapped to the action method without using the HTTP attribute?

A: For the action method, there are two ways to map the HTTP request. The first way is using the trait on the action method. The second way is naming the method that starts with the HTTP verb. Taking as an example, to define a GET method, can be defined as:

public void GetEmployee(int id)

 {

StudentRepository.Get(id);

}

As it can start with GET, the above-mentioned method can be automatically mapped with the GET request.

41. How to add certificates to a website?

A: To add the certificate to the website, you can follow the steps mentioned below:

  • You have to go to run type command mmc
  • Now click on Ok
  • The certificate add window is open now

42. Write a LINQ code for authenticating the user?

A: public static bool Login(string UN, string pwd)

{StudentDBEntities students = new StudentDBEntities()students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // students has more than one table}

43. How to navigate another page in jQuery?

A: using widow.location.href = “~/homw.html”;

44. How to enable SSL to ASP.NET web?

A: In order to enable SSL to ASP.NET web, you can click on project properties where you can see this option.

45. How to mention Roles and users using Authorize attribute in Web API?

// Restrict by Name

[Authorize(Users=”Shiva,Jai”)]

public class StudentController : ApiController{}

// Restrict by Role[Authorize(Roles=”Administrators”)]

public class StudnetController : ApiController{}

46. Can we apply constraints at the route level?

A: Yes, it can be applied.

[Route(“students/{id:int}”]

public User GetStudentById(int id) { … }

[Route(“students/{name}”]

public User GetStudentByName(string name) { … }

You can select the first route whenever the “id” segment of the URI is an integer. Or else, you can choose the second route.

47. How to enable attribute routing?

A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the WebApi config file.

public static void Register(HttpConfiguration config)

{

// Web API routes

config.MapHttpAttributeRoutes();

// Other Web API configuration not shown.

}

48. How parameters get the value in Web API?

A: Parameters get value in Web API in the following way:

  • Request body
  • URI
  • Custom Binding

49. Why is the “api/” segment used in Web API routing?

A: “api/” segment is used to avoid collisions with ASP.NET MVC routing

50. Is it possible to have MVC kind of routing in Web API?

A: It is possible to implement MVC kind of routing in Web API.

51. Where is the route defined in Web API?

A: It is placed in the App_Start directory.

App_Start –> WebApiConfig.cs

routes.MapHttpRoute(

name: “myroute”,

routeTemplate: “api/{controller}/{id}”,

defaults: new { id = RouteParameter.Optional }

);

52. How do you construct HtmlResponseMessage?

public class TestController : ApiController

A: To construct HtmlResponseMessage, you can consider the following way:

{

public HttpResponseMessage Get()

{

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, “value”);

response.Content = new StringContent(“Testing”, Encoding.Unicode);

response.Headers.CacheControl = new CacheControlHeaderValue()

{

MaxAge = TimeSpan.FromMinutes(20)

};

return response;

}

}

53. What are the default media types supported by Web API?

A: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON. The other media types supported can be done by writing a media formatter.

54. What is the disadvantage of “Other Return Types” in Web API?

A: The major disadvantage of “Other Return Types” in Web API is that error codes like 404 errors will not directly be returned.

55. What is the namespace for IHttpActionResult return type in Web API?

A: System.Web.Http.Results namespace

56. Why is Web API important?

We have several other technologies similar to Web API yet it is the most important and preferred over others for several reasons –

  • Web API has the most lightweight architecture and provides an easy interface for websites and client applications to access data. 
  • It uses low bandwidth. This makes it ideal for even small bandwidth devices, for instance, smartphones.
  • It can create non-SOAP-based HTTP services.
  • It can be consumed by a range of clients including web browsers, desktop and mobile applications.
  • Web API is based on HTTP which makes it convenient to define, consume or expose using REST-ful services. 
  • It fits best with HTTP verbs for operations such as Create, Read, Delete or Update.
  • Web API is more useful from the business point of view and finds its applications in UI/UX to increase web traffic and interest in a company’s services or products. 
  • It can support a plethora of text and media formats such as JSON, XML, etc. 
  • It can also support Open Data (OData) protocol. 
  • It is most suitable for the MVC pattern which makes it ideal for experienced developers in that pattern. 
  • It can be easily built using technologies such as ASP.NET, JAVA, etc. 
  • It is considered the best to create resource-oriented services. 

57. Which .NET framework supports Web API?

The .NET framework version supported by Web API includes version 4.0 and above. 

58. Which open-source library is supported by Web API for JSON serialization?

JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API. 

59. What are the advantages of using REST in Web API?

REST offers numerous advantages in Web API that include –

  • Lightweight architecture and easy to use 
  • Offers flexibility
  • Allows less data transfer between client and server
  • Handles various types of data formats
  • Its lightweight architecture makes it optimal for use in mobile applications
  • Uses simple HTTP calls for inter-machine communication

60. When do we need to choose ASP.NET Web API?

We are moving web-based services toward mobile applications in today’s hyper-connected digital world. That means we need a lightweight, secure, safe, and compatible API with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by many clients, including browsers and modern devices such as mobile phones, tablets, etc.

61. What do you understand by TestApi in Web API?

TestAPi in Web API refers to a utility library that allows developers to create testing tools as well as automate tests for a .NET application. 

62. How can we handle an error using HttpError in Web API?

The HttpError method is used in Web API to throw the response body’s error information. One can also use the “CreateErrorResponse” method along with this one. 

63. Can we consume Web API 2 in the C# console application?

Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any other application.

64. How to implement Basic Authentication in ASP.Net Web API?

Basic Authentication in ASP.Net Web API is one where the client will send a request using the word Basic with an Authorization header, followed by a base 64 encoded string.

The syntax for Basic Authentication –

Authorization: Basic username: password

65. Give an example of the parameter in Web API.

Parameters are used in Web API to determine the type of action you take on a particular resource. Each parameter consists of a name, value type and description that has the ability to influence the endpoint response.

You can use the query API to get information about various entities within a data source. 

The Get Method employs multiple primitive parameters. For instance, the Get method needs id parameter to get product details –

public IHttpActionResult GetProductMaster(int id)

{

ProductMaster productMaster = db.ProductMasters.Find(id);

if (productMaster == null)

{

return NotFound();

}

return Ok(productMaster);

}

In the same way, the Post method will require complex type parameters to post data to the server.

public IHttpActionResult PostProductMaster(ProductMaster productMaster)

{

if (!ModelState.IsValid)

{

return BadRequest(ModelState);

}

db.ProductMasters.Add(productMaster);

db.SaveChanges();

return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster);

}

Similarly PUT method will require primitive data type example for id and complex parameter i.e. ProductMaster class.

if (id != productMaster.id)

{

return BadRequest();

}

db.Entry(productMaster).State = EntityState.Modified;

try

{

db.SaveChanges();

}

catch (DbUpdateConcurrencyException)

{

if (!ProductMasterExists(id))

{

return NotFound();

}

else

{

throw;

}

}

66. Give an example to specify Web API Routing. 

Here is an example of Web API routing –

Config.Routes.MapHttpRoute( 

name: “MyRoute,”//route name 

routeTemplate: “api/{controller}/{action}/{id}”,//as you can see “API” is at the beginning. 

defaults: new { id = RouteParameter.Optional } 

); 

67. How to register an exception filter globally?

You can use the following code to register an exception filter globally –

GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());  

68. What are the different HTTP methods used in Web API?

Though there are a variety of HTTP verbs or methods, the most important and frequently used ones are GET, PUT, POST and DELETE.  

GET – It is used to retrieve information of the resource at a specified URI.

PUT – The PUT method is used to update the values of a resource at a specified URI.

POST –POST method is used to create a new request and send data to the respective server. 

DELETE –This method is used to remove the current resource at a specified URI.

The functionality of these HTTP verbs can be summed up using the acronym CRUD in which each letter corresponds to different action –

C stands for Create or POST (creating data)

R stands for Read or GET (data retrieval)

U stands for Update or PUT (updating data)

D stands for Delete or DELETE (deleting data)

Other less frequently used HTTP verbs or methods as per the requirement include –

HEAD –This method works the same way as the GET method and is primarily used to transfer the header section.

OPTIONS –This method helps identify and describe the communication option for a specific resource.

CONNECT –It is used to establish two-way communication between the server and the desired destination with the help of a given URI. 

TRACE – This method is used for diagnostic purposes to invoke a loop-back message along the target path and use that data for testing. 

69. What is HttpConfiguration in Web API?

HttpConfiguration refers to the global set of services used to override the behaviour of the default Web API. It has the following properties –

  • ParameterBindingRules
  • Formatters
  • MessageHandlers
  • DependencyResolver 
  • Services 

70. Explain the code snippet to show how we can return 404 errors from HttpError.

Here’s the Code for returning 404 error from HttpError – 

string message = string.Format(“TestCustomer id = {0} not found”, customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

71. What is the code used to register an exception filter from the action?

One can register an exception filter using the following code –

[NotImplExceptionFilter]

public TestCust GetMyTestCust (int custno)

{

//write the code

}

72. What are the testing tools or API for developing or testing web API?

  • CFX
  • Axis
  • Jersey API 
  • Restlet 

73. How can you pass multiple complex types in Web API?

Two ways to pass multiple complex types in Web API include – Newtonsoft array and using ArrayList. 

74. What is the code for passing ArrayList in .NET Web API?

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};

Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };

paramList.Add(c);

paramList.Add(p);

75. What is an HTTP status code? 

HTTP status codes are three-digit integers issued by the server in response to the request made by the client, where each number specifies a meaning. 

76. How are different HTTP Status Codes categorized?

All HTTP status codes are categorized into five classes. These include –

  • 1xx (Informational) – It indicates that the server has received a certain request and the process is continuing. 
  • 2xx (Successful)–It indicates that the request was successful and accepted. 
  • 3xx (Redirection)–It indicates that the request has been redirected and its completion will require further action or steps. 
  • 4xx (Client Error)–It indicates that the request for the web page cannot be reached as either it is unavailable or has bad syntax. 
  • 5xx (Server Error)–It indicates that the server was unable to complete a certain request even though the request seems valid. 

77. What is the commonly observed HTTP response status code?

There are many HTTP codes that are visible and others that are not visible at first but can be observed by the administrator using browser extensions or certain tools. Identifying and rectifying these errors is crucial to enhance the user experience and optimize search engine ranking over the web.  

Here are the most commonly seen HTTP status codes at a glance –

  • Status code 200 – request is ok.
  • Status code 201 – Created 
  • Status code 202 – Accepted 
  • Status code 204 – No content 
  • Status code 301 – Moved permanently 
  • Status code 400 – Bad request 
  • Status code 401 – Unauthorized 
  • Status code 403 – Forbidden 
  • Status code 404 – Not found 
  • Status code 500 – Internal server error 
  • Status code 502 – Bad gateway 
  • Status code 503 – Service Unavailable 

78. How do website owners avoid HTTP status codes?

To ensure that the website is running smoothly and offers an optimal user experience, the administrator or website owner has to work consistently to keep automatically generated error codes to the minimum and also to identify 404 errors. 

The 404 HTTP status code can be avoided by redirecting users by a 301 code to an alternative location such as the start page. The bounce-back rate of website visitors can also be decreased with the manual creation of error pages.

79. Name method that validates all controls on a page?

Page.Validate() method system is executed to validate all controls on a page.

80. What is the use of DelegatingHandler?

DelegatingHandler is a process used to develop a custom server-side HTTP message handler in ASI.Net Web API and chain message handlers together.

81. What do you mean by Internet Media Types?

Formerly known as the MIME type, it refers to the standard design for identifying content on the internet such as the type of information a piece of data contains.  

For example, if we receive a file over the email as an attachment, this identifier can be useful in knowing the media type of the attachment information contained in the header so that the browser can launch the appropriate plug-in.

It is a good practice to know information on media types as every internet media type has to comply with the following format –

[type]/[tree.] (Optional)[subtype][+suffix](Optional)[;parameters]

Each media type must have the ‘type’ and the ‘subtype’ that indicates the type of information it contains. For instance,   

Image– type/png- subtype

Application– type/rss- subtype+xml

82. Can a Web API return an HTML View?

Web API cannot return an HTML view. If you want to return views, it is best to use MVC. 

83. What is the status code for “Empty return type” in Web API?

The status code 204 will return empty content in the response payload body.  

84. Can you elaborate on different Web API filters?

Filters are used to add extra logic before or after specific stages of request processing within the Web API framework. 

There are different types of filters. Some built-in ones handle tasks such as authorization, response caching, etc. while custom filters can be created to handle concerns like error handling, authorization, etc.

Filter run within the ASP.Net pipeline, also referred to as the filter pipeline and various types of filter depending on the execution at a particular stage in this filter pipeline include –

  • Authentication filter –It helps to authenticate user details and HTTP requests.
  • Authorization filter –It runs before controller action to determine whether the user is authorized or not. 
  • Resource filter –It runs after authorization and runs code before the rest of the filter pipeline. For example – OnResourceExecuted runs code after the rest of the pipeline gets completed.  
  • Action filter –It is used to add extra logic before action gets executed and has the ability to change the result returned from a particular action. 
  • Exception filter –It is used when controller action throws unhandled errors that occur before the response body is written.
  • Override filter –it is used to change the action methods or other filters. 
  • Result filter –It runs code either before or after the execution of action results. 

85. What is the difference between ApiController and Controller?

ApiController specializes in returning data arranged in series and sent to the client.

public class TweetsController : ApiController

{

         // GET: /Api/Tweets/ 

        public List<Tweet> Get()

      {

          return Twitter.GetTweets();

       }

}

Controller, on the other hand, provides normal views and handles HTTP requests. 

public class TweetsController : Controller

        // GET: /Tweets/  [HttpGet]  public ActionResult Index()

       {   

           return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet); 

       }

}

86. What is the difference between XML and JSON?

XML is an acronym for eXtensible Markup Language and is designed to store and send data. JSON is an acronym for JavaScript Object Notation and is used to store and transfer data when data is sent from a server to a web page.

Except for storing data in a specific format, XLM does not do much whereas JSON is a lightweight and easy to understand format for storing data, widely used in JavaScript. 

87. What do you mean by Caching?

Caching refers to the technique of storing data in temporary storage in a cache for future use. It keeps copies of all frequently used data and files in the cache, which enables the website to render faster. It also helps improve scalability so that the data can be directly retrieved from the memory when needed.

The simplest cache in ASP.Net Web API is based on IMemoryCache.

Some key advantages of Caching include –

  • Minimizes database hits
  • Helps web pages render faster
  • Reduces network costs
  • Faster execution of process 
  • Highly efficient for both client and server
  • Reduces load time on the server
  • Best page management strategy to improve application’s performance 

88. What are the types of Caching?

There are different types of caching in ASP.NET Web API. These are –

  • Page output caching –This type of caching stores the recently used copy of the data in the memory cache to improve webpage performance. The cached output is fetched directly from the cache and sent to the application.

Here’s the code to implement page output caching –

<%@ OutputCache Duration=”30″ VaryByParam=”*” %>

  • Page fragment caching –In this form of caching, only fragments of data or web pages are cached instead of the entire page. It is helpful when the webpage contains dynamic and common sections and the user wants to cache some portions of it. 
  • Data caching –In this form of caching, data is stored in temporary storage so that it can be retrieved later. Here is the syntax to store data using the Cache API –

Cache[“key”] = “value”;

Web API FAQs

What is Web API and how it works?

A web API is an interface that allows you to access and manipulate data over the internet. It is typically used to access data from a web server, and can be used to create web applications or websites. It can be developed with the help of different technologies such as ASP.NET, or Java.

What is Web API in C# ?

A programming interface type that provides communication between software applications. It is often used to provide the interface for client applications and websites. It can also be used to access and save data from a database.

What are the types of API?

There are mainly four types of API used for web-applications. They are as follows:
– public,
– partner,
– private, and
– composite.

What is Web API example?

The full form of API is Application Programming Interface and it can extend the functionality of a web browser. An API would allow a third party such as Facebook to directly access the various functions of an external application, such as ordering a product on Amazon.

Why do we need Web API to develop RESTful services as we can also develop RESTful services using WCF?

Yes, it is absolutely possible to develop RESTful services using WCF (Windows Communication Foundation). But there are few reasons why people are moving from WCF to WEB API for developing restful services. Some of them are as follows.

  1. The Web API increases the TDD (Test Driven Development) approach in the development of RESTful services.
  2. If we want to develop RESTful services using WCF, then we need to do a lot of configuration settings, URI templates, contracts & endpoints. WCF basically used to develop SOA (Service Oriented Architecture) based applications.
What are the important return types supported in ASP.NET Web API?

In ASP.NET Web API Application, the controller action methods can return the following:

  1. Void – It simply returns empty content
  2. HttpResponseMessage – It will convert the response message to an HTTP message.
  3. IHttpActionResult – It internally calls the ExecuteAsync method to create an HttpResponseMessage
  4. Other types – You can also write the serialized return value into the response body. For example, you want to return Excel files.
Which .NET framework supports Web API?

The .NET Framework 4.0 and above version supports ASP.NET Web API.

Which protocol ASP.NET Web API supports?

The ASP.NET Web App supports the one and only HTTP protocol.

ASP.NET Web API uses which open-source library for JSON serialization?

The ASP.NET Web API Framework uses the Json.NET library for JSON serialization.

By default, Web API sends an HTTP response with which status code for an uncaught exception?

It will send the response with HTTP Status 500 – Internal Server Error

How do you construct HtmlResponseMessage in ASP.NET Web API?

public class HomeController : ApiController

{

public HttpResponseMessage Get()

{

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, “value”);

response.Content = new StringContent(“Testing”, Encoding.Unicode);

response.Headers.CacheControl = new CacheControlHeaderValue()

{

MaxAge = TimeSpan.FromMinutes(20)

};

return response;

}

}

What is Routing in ASP.NET Web API?

The ASP.NET Web API Routing module is responsible for mapping the incoming HTTP requests to a particular controller action method. Based on the incoming requests the Web API uses URI and HTTP verbs to select the action method. Please read our Routing in ASP.NET Web API article for more detail.

How the Web API Framework handle an incoming HTTP Request?

When the ASP.NET Web API Framework receives an HTTP request, it tries to match the URI against one of the route templates available in the routing table. If no route template matches the URI, then Web API Framework returns a 404 error to the client who actually makes the request. Once a matching route is found in the Route Table, the Web API Framework then selects the controller and the action to be executed.

What is SOAP?

SOAP stands for Simple Object Access Protocol and it is an XML-based protocol. SOAP has specifications for both stateless and state-full implementation. It is also an XML-based messaging protocol for exchanging information among computers. The SOAP message consists of an envelope that includes SOAP headers and body to store the actual information we want to send. It supports different types of protocols such as HTTP, TCP, etc.

How Can we assign an alias name for ASP.NET Web API Action?

We can give alias name for Web API action using the “ActionName” attribute as follows: 

[HttpPost]

[ActionName(“StudentAdd”)]

public void AddStudents(Student aStudent)

{

StudentRepository.AddStudent(aStudent);

}

For more detail about default naming convention and custom action names, please read our Custom Action Name article.

What is Content Negotiation in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. One of the standards of the REST service is that the client should have the ability to decide in which format they want the response – whether they want the response in XML or JSON etc. This is called Content Negotiation in Web API. Web API Content Negotiation means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. That’s why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. Please read our Web API Content Negotiation article where we discussed this concept in detail with examples.

What is CORS?

Before understanding CORS, first, we need to understand the same-origin policy. Browsers allow a web page to make AJAX requests only within the same domain. The Browsers does not allow a web page from making AJAX requests to another domain. This is called the same-origin policy.

CORS is a W3C standard that allows us to get away from the same-origin policy adopted by the browsers that restrict access from making AJAX requests from one domain to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use). Please read our Cross-Origin Resource Sharing (CORS) in Web API article where we discussed this concept in detail with examples.

What is Web API Attribute Routing?

The ASP.NET Web API 2 supports a new type of routing called attribute routing. Attribute routing means attributes are used to define routes. The Attribute routing provides more control over the URIs by defining routes directly on the actions and controllers. Please read our Attribute Routing in Web API article where we discussed this concept in detail with examples.

Why do we need Attribute Routing in Web API?

The convention-based routing makes it hard to support certain URI patterns that are common in RESTful APIs. For example, resources often contain child resources such as Customers have orders, movies have actors, books have authors, etc. It’s natural to create URIs that reflect these relations.

What is Authentication and Authorization in Web API?

Once you create a Web API Service, then the most important thing that you need to take care of is security means you need to control access to your Web API Services.

Authentication is the process of identifying the user. For example, one user let’s say James logs in with his username and password, and the server uses his username and password to authenticate James.

Authorization is the process of deciding whether the authenticated user is allowed to perform an action on a specific resource (Web API Resource) or not. For example, James (who is an authenticated user) has the permission to get a resource but does not have the permission to create a resource. Please read our Authentication and Authorization in ASP.NET Web API article where we discussed this concept in detail with examples.

What is an HTTP Message handler in ASP.NET Web API Application?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. An HTTP Message Handler in Web API is a class that receives an HTTP request and returns an HTTP response. The Message Handler is derived from the abstract HttpMessageHandler class. The HTTP Message handlers are good for cross-cutting concerns (such as authentication and authorization) that operate at the level of HTTP messages rather than controller actions. For example, a Custom HTTP Message handler might do the following things in a Web API Application.

  1. Read or modify the HTTP request headers.
  2. Add a response header to the HTTP response.
  3. Validate the requests before they reach the controller (i.e. Authentication and Authorization).

Please read our HTTP Message Handler in the Web API article where we discussed this concept in detail with multiple real-time examples.

Why Web API versioning is required?

Once you develop and deploy a Web API service then different clients start consuming your Web API services. As you know, day by day the business grows and once the business grows then the requirement may change, and once the requirement change then you may need to change the services as well, but the important thing you need to keep in mind is that you need to do the changes to the services in such a way that it should not break any existing client applications who already consuming your services.

This is the ideal scenario when the Web API versioning plays an important role. You need to keep the existing services as it is so that the existing client applications will not break, they worked as it is, and you need to develop a new version of the Web API service which will start consuming by the new client applications. Please read our Web API Versioning article where we discussed this concept in detail with examples.

What are the Different options available in Web API to maintain the versioning?

The different options that are available to maintain versioning are as follows

  1. URI’s
  2. Query String
  3. Version Header
  4. Accept Header
  5. Media Type
What are Request Verbs or HTTP Verbs?

In RESTful service, we can perform all types of CRUD (Create, Read, Update, Delete) Operation. In REST architecture, it is suggested to have a specific Request Verb or HTTP verb on the specific type of the call made to the server. Popular Request Verbs or HTTP Verbs are mentioned below:

  1. HTTP GET: This HTTP verb is Used to get the resource only.
  2. HTTP POST: This HTTP verb is Used to create a new resource.
  3. HTTP PUT: This HTTP verb is Used to update an existing resource.
  4. HTTP PATCH: This HTTP verb is Used to update an existing resource.
  5. HTTP DELETE: This HTTP verb is Used to Delete an existing resource.

Note: PUT and PATCH are not similar. If you are updating few columns in your database then use PATCG and if you are updating all the data then use PUT.

What do you mean by Parameter Binding in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The Parameter Binding means how the Web API Framework binds the incoming HTTP request data to the parameters of an action method of a Web API controller. The ASP.NET Web API action methods can take one or more parameters of different types. An action method parameter can be either of a complex type or primitive type. The Web API Framework binds the action method parameters either with the URL’s query string or from the request body of the incoming HTTP Request based on the parameter type.

By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string. And if the action method parameter type is a complex type then Web API Framework tries to get the value from the request body.

But we can change this default behavior of the parameter binding process by using [FromBody] and [FromUri] attributes.

  1. FromBody: This will force the Web API Framework to get the value from the request body.
  2. FromUri: This will force the Web API Framework to get the data from the URI (i.e. Route data or Query String)

Please read our Parameter Binding in ASP.NET Web API article where we discussed this concept in detail with examples.

What is the use of Authorize Attribute?

The ASP.NET Web API Framework provided a built-in authorization filter, i.e. Authorize Attribute. This filter checks whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.

How to Enable CORS in Web API?

If we are going to consume the ASP.NET Web API Service using Jquery Ajax from another domain, then we need to enable CORS in the Web API application. Without enabling CORS, it is not possible to access the service from another domain using AJAX call. Enabling CORS in Web API is a two steps process.

Step1: Install Microsoft.AspNet.WebApi.Cors package.

Step2: Once you installed the Microsoft.AspNet.WebApi.Corspackage then includes the following 2 lines of code in the Register() method of WebApiConfig class which is present inside the App_Start folder of your project.

EnableCorsAttribute cors = new EnableCorsAttribute(“*”, “*”, “*”);
config.EnableCors();

What is Basic HTTP Authentication?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client needs to pass the username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password: based encoded. Please read our Basic Authentication in ASP.NET Web API article where we discussed this concept in detail with examples.

What is ASP.Net identity?

ASP.Net identity is the membership management framework given by Microsoft which can be easily integrated with ASP.NET Web API. This helps us in building a secure HTTP service.

What is Token Based Authentication in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Nowadays, the use of Web API is increasing in a rapid manner. So as a developer we should know how to develop Web APIs. Only developing Web APIs is not enough if there is no security. So, it also very important to implement security for all types of clients (such as Browsers, Mobile Devices, Desktop applications, and IoTs) who are going to use our Web API services.

The most preferred approach nowadays to secure the Web API resources is by authenticating the users in the Web API server by using the signed token (which contains enough information to identify a particular user) which needs to be sent to the server by the client in each and every request. This is called the Token-Based Authentication approach.

How does the Token-Based Authentication work?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. In order to understand how token-based authentication works, please have a look at the following diagram.

The Token-Based Authentication works as Follows:

  1. The user enters his credentials (i.e. the username and password) into the client (here client means the browser or mobile devices, etc).
  2. The client then sends these credentials (i.e. username and password) to the Authorization Server.
  3. Then the Authorization Server authenticates the client credentials (i.e. username and password) and generates and returns an access token. This Access Token contains enough information to identify a user and also contains the token expiry time.
  4. The client application then includes the Access Token in the Authorization header of the HTTP request to access the restricted resources from the Resource Server until the token is expired.

Please read our Token Based Authentication in Web API article where we discussed this concept in detail with examples.

What is a Refresh Token?

Refresh Token is a special kind of token that can be used to obtain a new renewed access token that allows access to the protected resources. You can request the new access tokens by using the Refresh Token in Web API until the Refresh Token is blacklisted.

Why we need Refresh Token in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The idea of using the refresh token is to issue a short-lived access token (up to 30 minutes) for the first time and then use the refresh token to obtain a new access token and use that access token to access the protected resources.

So, the user needs to provide the username and password along with the client info (i.e. the client id and client secret) to authenticate himself, and if the information provided by the user is valid, then a response contains a short-lived access token along with a long-lived refresh token gets generated. 

The refresh token is not an access token it is just an identifier for the access token. Now once the access token is expired, the user can use the refresh token to obtain another short-lived access token and so on.

Please read our Refresh Token in the Web API article where we discussed this concept in detail with examples.

What is HMAC Authentication?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The HMAC stands for Hash-based Message Authentication Code. From the full form of HMAC, we need to understand two things one is Message Authentication Code and the other one is Hash-Based. So HMAC is a mechanism that is used for creating a Message Authentication Code by using a Hash Function.

The most important thing that we need to keep in mind is that while generating the Message Authentication Code using Hash Function we need to use a Shared Secret Key. Moreover, the Shared Secret Key must be shared between the Client and the Server involved in sending and receiving the data. 

Why do we need HMAC Authentication in Web API?

The main uses of HMAC Authentication in Web API are as follows.

  1. Data integrity: It means the data sent by the client to the server has not tampered.
  2. Request origination: The request comes to the server from a trusted client.
  3. Not a replay request: The request is not captured by an intruder and being replayed.

59 thoughts on “Asp.Net Web API with 50 Plus Interview Questions”

  1. I have learn a few excellent stuff here. Certainly worth bookmarking for revisiting.
    I surprise how a lot effort you place to create this kind of magnificent informative website.

  2. Howdy would you mind stating which blog platform you’re using?
    I’m going to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different
    then most blogs and I’m looking for something unique.
    P.S My apologies for getting off-topic but I had to ask!

    Also visit my webpage :: KASACK

  3. Nice post. I was checking continuously this blog and I am impressed!
    Very useful information particularly the last part
    🙂 I care for such information much. I was looking for this certain information for a very long time.

    Thank you and good luck.

  4. Have you ever considered about adding a little bit more
    than just your articles? I mean, what you
    say is important and all. Nevertheless think about if you added some great images or video clips to give your posts more,
    “pop”! Your content is excellent but with images and
    videos, this site could definitely be one of the most beneficial in its field.
    Superb blog!

  5. I’m impressed, I must say. Seldom do I come across a blog that’s equally educative and entertaining,
    and without a doubt, you’ve hit the nail on the head. The problem
    is something that not enough people are speaking intelligently about.
    I am very happy I came across this during my search for something regarding this.

  6. Enhance your allure and spark unforgettable
    connections. Discover the essence of attraction, confidence, and romance with our
    unique blend designed for vibrant, passionate moments.

    Ignite your charm and let chemistry work its magic. Feel the difference, feel the desire.

  7. Наша команда квалифицированных мастеров завершена предоставлять вам перспективные приемы, которые не только ассигнуруют прочную протекцию от холода, но и подарят вашему собственности элегантный вид.
    Мы трудимся с последовательными веществами, заверяя долгий продолжительность службы и великолепные выходы. Изолирование облицовки – это не только экономия тепла на подогреве, но и забота о экосистеме. Сберегательные технологии, каковые мы внедряем, способствуют не только жилищу, но и сохранению природных ресурсов.
    Самое ключевое: Сколько стоит утепление фасада у нас стартует всего от 1250 рублей за м²! Это доступное решение, которое изменит ваш домашний уголок в реальный тепловой уголок с минимальными затратами.
    Наши труды – это не единственно теплоизоляция, это составление площади, в где каждый деталь символизирует ваш личный стиль. Мы примем во внимание все твои желания, чтобы осуществить ваш дом еще больше дружелюбным и привлекательным.
    Подробнее на http://www.ppu-prof.ru
    Не откладывайте заботу о своем корпусе на потом! Обращайтесь к экспертам, и мы сделаем ваш жилище не только согретым, но и моднее. Заинтересовались? Подробнее о наших трудах вы можете узнать на сайте компании. Добро пожаловать в сферу удобства и уровня.

  8. I’ve been browsing online more than 3 hours these days, yet I by no means discovered any interesting article
    like yours. It’s beautiful price enough for me. Personally, if all webmasters and bloggers made just right
    content as you probably did, the internet will be a lot more helpful
    than ever before.

  9. Its like you read my thoughts! You seem to grasp so much about this, like you wrote
    the ebook in it or something. I believe that you just could do with some p.c.
    to force the message house a little bit, but instead of that, this is wonderful blog.
    A great read. I’ll definitely be back.
    Sample Templates
    Sample TemplateExcel Template
    Best TemplateFree Sample Templates
    Download TemplatesMustervorlagenBestTemplatess

    Look into my web site … Kleurplaten

  10. I blog often and I truly thank you for your content. This great article has really peaked
    my interest. I am going to book mark your site and keep checking for new information about once a week.
    I opted in for your RSS feed too.

  11. I do believe all of the concepts you have introduced to your post.
    They’re very convincing and can certainly work. Nonetheless,
    the posts are too brief for starters. Could you please extend them a
    little from subsequent time? Thank you for the post.

  12. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored
    material stylish. nonetheless, you command get bought an shakiness
    over that you wish be delivering the following.
    unwell unquestionably come further formerly again as exactly the same nearly a lot
    often inside case you shield this hike.

  13. It is the best time to make some plans for the future
    and it is time to be happy. I have read this post and if I could I desire to suggest you some interesting things or tips.
    Perhaps you could write next articles referring to this article.
    I want to read more things about it!

  14. What’s Taking place i am new to this, I stumbled upon this I’ve
    discovered It positively helpful and it has helped me out loads.
    I am hoping to give a contribution & help other users like its aided me.
    Good job.

  15. Hi there would you mind sharing which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m
    having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking
    for something unique. P.S Apologies for
    being off-topic but I had to ask!

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com