WEB API Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

WEB API Interview Questions in .NET

Question 1.
What is ASP.Net Web API?
Web API is the Microsoft open source technology to develop REST services which is based on HTTP protocol. ASP.Net Web API is a framework to build, consume HTTP-based services. Web API can be consumed by a wide range of clients such as web browsers and mobile applications.

Question 2.
WCF REST API is good for Message Queue, duplex communication, one way messaging. Web API is good for HTTP-based services.
Web API is the best fit with the MVC pattern which is the major benefit of the Web API.
WCF will support SOAP and XML format, while Web API can support any media format including JSON, XML.
WCF is good for developing service-oriented applications and ASP.Net Web API is perfect for building HTTP services.
WCF can support HTTP, TCP, Named Pipes as the protocol on another side Web API can support HTTP protocol only.
WEB API is easy for experienced developers in the MVC pattern.
WCF requires lots of configuration to run, while Web API is simple and no configuration is required to run.


1. It is a framework used to build or develop service-oriented applications.
2. WCF will only be consumed by clients, which will understand XML. WCF can support protocols such as – HTTP, TCP, Named Pipes, etc.


1. It is a framework that will help us for building/developing HTTP services
2. Web API is an open source platform.
3. It will support most of the MVC features that will keep Web API over WCF.

Question 3.
The advantage of Web API over WCF services.
The disadvantage of WCF over Web API is that WCF will require a lot of configuration to work, but in Web API is simple and no extra configuration.

Question 4.
Advantages of using ASP.Net Web API.
Using ASP.NET Web API has following advantages :

1. It will work as HTTP works using standard HTTP verbs like GET, POST, PUT, DELETE, etc. for all CRUD operations
2. Complete support for routing
3. Response will be generated in JSON or XML format using MediaTypeFormatter
4. It has the ability to be hosted in IIS and self-host outside of IIS
5.Supports Model binding and Validation
6. Support for OData

Question 5.
What are the various return types in ASP.Net Web API?
Following are the various return types in ASP.Net Web API

1. HttpResponseMessage
2. IHttpActionResult
3. Void
4. Other Type – string, int, or other entity types.

Question 6.
What is ASP.Net Web API routing?
Routing in ASP.Net Web API is the process that will decide which action and which controller should be called.
There are following ways to implement routing in Web API.
1. Convention based routing
2. Attribute based routing

Question 7.
What are Media type formatter in Web API?
Following are Media type formatter in Web API:
1. MediaTypeFormatter- Base class for handling serializing and deserializing strongly- typed objects.
2. BefferedMediaTypeFormatter- Represents a helper class for allowing asynchronous formatter on top of the asynchronous formatter infrastructure.

Question 8.
CORS issue in Web API?
CORS will stand for Cross-Origin Resource Sharing. CORS will resolve the same-origin restriction for JavaScript. The same Origin means that a JavaScript will only make AJAX call for the web pages within the same origin.

We must install CORS nuget package using Package Manager Console to enable CORS in Web API.

Open WebAPIConfig.es file
add config.EnableCors( );

Add EnableCors attribute to the Controller class and define the origin.
[EnableCors(origins: headers: methods: “*”)].

Question 9.
How to secure an ASP.Net Web API?
Web API security means, We required to control Web API and decide who can access the API and who will not access the Web API. using Token based authentication .Setting proper authentication and authorization makes it safe.

Question 10.
Http Get vs Http Post
GET and POST is two important HTTP verbs. HTTP (HyperText Transfer Protocol) can manage the request-response between client and server.
GET parameters is included in URL
POST parameter is included in the body

Get request will not make any changes to the server
POST is for making changes to the server

GET request is idempotent
POST request is non-idempotent.
In a GET request, we will send data in plain text.
In a POST request, we will send binary as well as text data.

Question 11.
Can Web API be used with traditional ASP.Net Forms?
Yes, Web API will be used with ASP.Net Forms.
We will add Web API Controller and manage to route in Application Start method in Global.asax file.

Question 12.
Exception filters in ASP.Net Web API
Exception filter in Web API will implement lExceptionFilters interface. Web API Exception filters can execute when an action will throw an exception at any stage.

Question 13.
Do we return View from ASP.Net Web API?
No, it will not be possible in Web API as Web API will create HTTP based service. It is available in MVC application.

Question 14.
What’s new in ASP.Net Web API 2.0?
The following features are introduced in ASP.NET Web API framework v2.0:
1. Attribute Routing
2. External Authentication
3. CORS (Cross-Orrgrn Resource Sharing)
4. OWIN (Open Web Interface for .NET) Self Hosting
5. IHttpActfonResult
6. Web API OData
Following new features are included in Web API 2 –

Attribute-based routing
public string Get(int productid)
return "value";
CORS (Cross-Origin Resource Sharing) support
OWIN to Self Host Web API
Web API OData

Question 15.
How do we restrict access to methods with an HTTP verb in Web API?
We will just add an attribute as shown below – [HttpGet]

public HttpResponseMessage Test( )
HttpResponseMessage response = new HttpResponseMessage( );
return response;
public void Save([FromBody]string value)


Question 16.
How do we make sure that Web API returns data in JSON format only?
To make sure that web API returns data in JSON format only this open “WebApiConfig.es” file and add below line : config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/json”))

Question 17.
How to provide Alias name for an action method in Web API?
We can provide Alias name by adding an attribute ActionName


// POST a pi/
public void Post([FromBody]string value)

Question 18.
How we can handle errors in Web API?
Following classes will help to handle the exception in ASP.Net Web API.
1. ExceptionFilters
2. HttpError
3. HttpResponseException .

Question 19.
How to host Web API?
Web API application will be hosted in two ways :
1. Self Hosting – Web API will be hosted in Console Application or Windows Service.
2. IIS Hosting – Web API will also be hosted with IIS and the process can be similar to hosting a website.

Question 20.
How to consume Web API using HttpCIient?
HttpCIient will be introduced in HttpCIient class for communicating with ASP.Net Web API. This HttpCIient class will be used in a console application or in an MVC application. Using Entity Framework, the implementation of Web API CRUD operation in MVC application .

Question 21.
Parameters in Web API
Action methods in Web API will accept parameters as a query string in URL or it will accept with the request body.
For example to fetch particular product details the Get method will require an id parameter.

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 parameter to post data to the server.

public IHttpActionResult PostProductMaster(ProductMaster productMaster)
if (IModelState.lsValid)
return BadRequest(ModelState);
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
catch (DbUpdateConcurrencyException)
if (IProductMasterExists(id))
return NotFoundQ;
} return StatusCode(HttpStatusCode.NoContent);

Question 22.
Explain oData with ASP.Net Web API.
OData is stand for Open Data Protocol, it will be a Rest-based data access protocol. OData will provide a way for querying and manipulating data using CRUD operation. ASP.Net Web API will support OData V3 and V4.
For using OData in ASP.Net Web API, We required the OData package by running below command in Package Manager Console.

Install-Package Microsoft.AspNet.Odata

Question 23.
Can we consume Web API 2 in C# console application?
Yes, we consume Web API 2 in Console Application, Angular JS, MVC or any other application.

Question 24.
Perform Web API 2 CRUD operation using Entity Framework.
We can perform CRUD operation using entity framework with Web API. We will read one of my blog for seeing the implementation of Web API 2 CRUD operation using Entity Framework.

Question 25.
How to Enable HTTPS in Web API?
Steps to enable HTTPS in ASP.NET Web API,

  • Write a custom class which is inherited from AuthorizationFilterAttribute
  • Register that class in ASP.NET Web API Config
  • Apply [RequireHttps] attribute on API controller actions.
  • Create a temporary certificate for SSL.
  • Install the certificate
  • Enable HTTPS support to the development server in Visual Studio.

Write a custom class which is inherited from AuthorizationFilterAttribute

Write a custom class as shown below.

 public class RequireHttpsAttribute: AuthorizationFilterAttribute
 public override void OnAuthorization (HttpActionContext actionContext)
If (act'ronContext.Request.RequestUri.Scheme ! = Uri.UrrScherrreHttps)
 actionContext.Response = new HttpResponseMessage (System.Net.HttpSta
ReasonPhrase = "HTTPS Required for this call"

Register that class in ASP.NET Web API Config

To register custom HTTP filter class in web API configuration here are the settings.

// Web API configuration and services
config.Filters.Add(new RequireHttpsAttribute( ));

Remember this a global setting and will require all controller methods to run on HTTPS.

If we want to have a few methods to run on HTTP then in that case, just disable this setting. And use the [Requirehttps] attribute for individual methods.

Apply [RequireHttpsj attribute on API controller actions.

public IEnumerable<string> Get ()
return new string [] {"valuel", "value2"};

We need to use this [RequireHttps] attribute only in case we need to enable HTTPS only for selective API controller actions. Otherwise Web API configuration global settings are enough.

But if are targeting only a few API methods to run on HTTPS then we must disable the global configuration. Otherwise, all method calls will demand HTTPS.

Create a temporary certificate for SSL

To create a temp certificate run the following command in the command prompt.

makecert.exe -n ”CN=Development CA” -r -sv TempCA.pvk TempCA.cer

Once the certificate is created it will be saved on your machine at the path selected in the command prompt windows.

Now, we need to install it.

Install the certificate

For installing the certificate on your local machine, you need to do the following steps.

  • Open MMC (Management console) window
  • Then go to File – > Add or Remove Snap Ins
  • Then select Certificates from available Snap Ins
  • Then click on the ADD button
  • Then select Computer account in the window pane that opens
  • Then select Local Computer Account
  • Then click next and OK

Now the certificate snap is added to MMC.

Now we need to install the certificate by selecting it in a snap.

For that,

  • Go to Certificates; expand it.
  • Then Select “Trusted root certification Authorities”
  • Then Select Action-> All Tasks-> Imports
  • Select the certificate and finish.

Now, a temporary certificate is installed on your computer.

This certificate will be used for SSL communication on your machine, but apart frbtn !!> installation, you don’t need to do anything with respect to certificates.

Now, the next step is to enable Https for the development server.

Enable HTTPS support to development server in Visual Studio

For that do the following:

  • Open your web API solution in Visual Studio,
  • Then select the web API project in Solution Explorer.
  • Select View Menu in Visual Studio
  • Now select “Properties window” or click F4.
  • A window pane will open.
  • There select “SSL Enabled” property and set it to true

Now, the development server is ready to work with HTTPS too.

Question 26.
How to implement Basic Authentication in ASP.Net Web API?
Basic Authentication is a simple authentication mechanism where the client will send request with an Authorization header with word Basic. In Basic Authentication, Authorization header will contain a word Basic followed by base 64 encoded string.
The syntax for Basic Authentication –

Authorization: Basic username: password

Question 27.
What Is Token Based Authentication in Web API?
A better approach for securing .Net Web API is by authenticating users by a signed token which is called token-based approach.
In Token-based authentication –
A client will send a request to the server with the credential. If the provided credential is valid then the server will send a token to the client.
This token will contain user details for the identification with an expiry time.
Once the client will received the token, it will use this token to access API resources wherever authentication requires.
To implement Token-based authentication we need to install Microsoft.Owin from Nuget package.

Question 28.
What is content negotiation in .Net Web API?
In ASP.Net Web API, content negotiation will be performed at the server-side. This is for determining the media type formatter for returning the response to an incoming request.

Question 29.
What is ASP.Net identity?
ASP.Net identity is the membership management framework provided by Microsoft which will be easily integrated with Web API. This will help us in building a secure HTTP service.

Question 30.
What is Bearer Authenticating in .Net Web API?
Bearer authentication is also called as Token-based authentication.

Question 31.
What is Rest?
REST is stand for Representational State Transfer. This is an architectural pattern to exchange data over a distributed environment. REST architectural pattern can treat each service as a resource and a client will access these resources by using HTTP protocol methods such as GET, POST, PUT, and DELETE.

Question 32.
What is Not Rest?
Following is Not Rest:
1. A protocol
2. A standard
3. A replacement of SOAP

Question 33.
When to choose WCF and Web API over the other?
WCF (Windows Communication Foundation) is available in .NET to create both SOAP and REST services. A lot of configuration is needed to turn a WCF service into a REST service. To create REST services is ASP.NET Web API is better choice.

WCF is suited to build services which are transport/protocol independent. For example, we want to build a single service which can be consumed by 2 different clients – a Java client and .NET client. Java client will want the transport protocol to be HTTP and message format to be XML for interoperability, whereas the .NET client will expect the protocol to be TCP and the message format to be binary for performance. WCF is the right choice for this. Create a single WCF service, and configure 2 endpoints one for each client (one for the Java client and the other for the .NET client).

It is a bit more complex and configuration can be a headache to use WCF to create REST services. If we are stuck with .NET 3.5 or we have an existing SOAP service we should support but required to add REST to reach more clients, then use WCF.
If we will not have the limitation of .NET 3.5 and we required to create a brand new restful service then use ASP.NET Web API.

Question 34.
When do we need to choose Web API?
Today, a web-based application is not sufficient to reach its customers. Peoples are using iPhone, mobile, tablets etc. devices in their daily life. These devices will have a lot of apps to make their life easy. Actually, we are moving towards apps world.
Therefore, if we want for exposing our service data to the browsers to all these modern devices apps in a fast and simple way, we will have an API which will be compatible with browsers as well as all these devices.

The ASP.NET WEB API is a great framework to build HTTP services which will be consumed by a broad range of clients including browsers, mobiles, iPhone and tablets. WEB API is open source and an ideal platform to build REST-full services over the .NET Framework.

Question 35.
What are RESTful services?
REST is stand for Representational State Transfer. The REST was first introduced in the year 2000 by Roy Fielding as part of his doctoral dissertation. REST is an architectural pattern to exchange the data over a distributed environment. REST architectural pattern will treat each service as a resource and a client will access these resources by using HTTP protocol methods such as GET, POST, PUT, and DELETE. The REST architectural pattern will specific a set of constraints which a system should adhere to. Following are the REST constraints:

1. Client-Server constraint –
This is the first constraint. This constraint will specify which a Client will send a request to the server and the server will send a response back to the client. This separation of concerns can support the independent development of both client-side and server-side logic. That means client application and server application can be developed separately without any dependency on each other. A client will only know resource URIs and that’s all. Severs and clients will also be replaced and developed independently as long as the interface between them will not be altered.

Stateless constraint –
The next constraint is the stateless constraint. The stateless constraint will specify that the communication between the client and the server should be stateless between requests. We will not be storing anything on the server related to the client. The request from the client will contain all the necessary information for the server for processing that request. This will ensure that each request will be treated independently by the server.

Cacheable constraint –
Some data will be provided by the server such as the list of products, or list of departments in a company will not change that often. This constraint states that let the client know how long this data will be good for therefore the client will not have to come back to the server for that data over and over again.

Uniform Interface constraint-
The uniform interface constraint will define an interface between the client and the server. To understand the uniform interface constraint, we required to understand what a resource is and the HTTP verbs – GET, PUT, POST and DELETE. In the context of a REST API, resources typically represent data entities. The product, Employee, Customer, etc. are all resources. The HTTP verb (GET, PUT, POST, and DELETE) which is sent with each request informs the API what to do with the resource. Each resource will be identified by a specific URI (Uniform Resource Identifier).

Layered System-
REST will allow us to use a layered system architecture where we can deploy the APIs in server A, and will store data on server B and authenticate requests in server C. For example, a client will not ordinarily state whether it will be connected directly to the server or to an intermediary along the way.
1. SOAP Performance is slow as compared to REST.

Question 36.
What are the differences between REST and SOAP?
The difference between REST and SOAP is following:
1. SOAP will stand for Simple Object Access Protocol whereas REST stands for Representational State Transfer.
2. The SOAP is an XML which is based protocol whereas REST will not a protocol but it is an architectural pattern example for resource-based architecture.
3. SOAP has specifications for both stateless and state-full implementation whereas REST will be completely stateless.
4. SOAP will enforce message format as XML whereas REST will not enforce message format as XML or JSON.
5. The SOAP message is consist of an envelope that will include SOAP headers and body for storing the actual information we required for sending whereas REST will use the HTTP build-in headers with a variety of media-types for storing the information and it will use the HTTP GET, POST, PUT and DELETE methods for performing CRUD operations.
6. SOAP will use interfaces and named operations for exposing the service whereas to expose resources (service) REST will use URI and methods such as GET, PUT, POST, DELETE.

Question 37.
What are the differences between ASP.NET MVC and ASP.NET Web API?
Following are some of the differences between MVC and Web API

1. MVC is used for creating a web app, in which we will build web pages.
2. For JSON it can return JSONResult from an action method.
3. All requests will be mapped to the respective action methods.

1. This is used for creating a service using HTTP verbs
2. This will return XML or JSON to the client.
3. All request will be mapped to actions using HTTP verbs.
There are some following differences between ASP.NET MVC and WEB API:
1. MVC can be used for creating web applications which will return both views and data but ASP.NET WEB API will be used for creating rest full HTTP services with the easy and simple way which will return only data, not view.
2. WEB API will help for building REST-full services over the .NET Framework and it will also support content-negotiation that is not in MVC.
3. WEB API will also take care of returning data in a particular format such as JSON, XML or any other based upon the Accept header in the request. MVC return data in JSON format using JsonResult.
4. In WEB API the request will be mapped to the actions based on HTTP verbs but in MVC it will be mapped to actions name.
5. We will mix WEB API and MVC controller in a single project for handling advanced AJAX requests which will return data in JSON, XML or any others format and building a full-blown HTTP service. Typically, this can be called WEB API self-hosting.
6. WEB API is lightweight architecture and will except the web application, it will also be used with smartphone apps.

Question 38.
Is it true that ASP.NET Web API has replaced WCF?
No, t ASP.NET Web API has not replaced WCF. It is an other way of building non-SOAP based services, for example, plain XML or JSON string, etc.
Yes, it will have some added advantages such as utilizing the full features of HTTP and reaching more clients like mobile devices, etc.
WCF is a better choice for the following scenarios:
1. If we are intended to use transport other than HTTP, example for TCP, UDP or Named Pipes
2. Message Queuing scenario will be using MSMQ.
3. One-way communication or Duplex communication.

Question 39.
Explain media Formatters in Web API 2
Web API will handle JSON and XML formats which is based on the Accept and Content-
Type header values.
The Media-Type Formatters are classes which will be responsible for serializing request/response data therefore that web API will understand the request data format and send data in the format that client expects.
Technically MediaTypeFormatter is an abstract class from which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from. JsonMediaTypeFormatter which will handle JSON and XmlMediaTypeFormatter handles XML.

Question 40.
How to return only JSON from ASP.NET Web API Service irrespective of the Accept header value?
The following line should be included in Register!) method of WebApiConfig.es file in App_Start folder. This line of code will completely remove XmlFormatter that will force ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Use this technique when we required our service for supporting only JSON and not XML.

With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service will always going to return JSON. config. Formatters. Remove(config.Formatters.XmlFormatter);

Question 41.
How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser?
We can return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser in following way:
1. when a request will be issued from the browser, the web API service will return JSON instead of XML.
2. When a request can be issued from a tool such as a fiddler the Accept header value will be be respected. This means if the Accept header will set to application/xml the service should return XML and if it will be set to application/json the service should return JSON.
There are 2 ways to achieve this

The following line should be included in Register!) method of WebApiConfig.es file in App_Start folder. This states ASP.NET Web API to use JsonFormatter when a request will be made for text/html which is the default for most browsers. The problem with this approach is that the Content-Type header of the response will be set to text/html which is misleading.

The following clas should be included in WebApiConfig.es file in App_Start folder.
Register Formatter:
Place the following line in RegisterQ method of WebApiConfig.es file in App_Start folder

Question 42.
Which protocol is supported by WebAPI?
WebAPI will supports only HTTP protocol.So it will be consumed by any client which can support HTTP protocol.

Question 43.
What are the Similarities between MVC and WebAPI.
Both are based on the same principle of Separation of concerns.
• Both have similar concepts such as routing,controllers and models.

Question 44.
Differences between MVC and WebAPI
MVC will be used to develop applications which have User Interface.Views in MVC can be used for developing user interface.
• WebAPI will be used to develop HTTP services.Other applications call the WebAPI methods to fetch the data.

Question 45.
Who can consume WebAPI?
Following can consumes WebAPI:

  • WebAPI will be consumed by any client which can support HTTP verbs like GET,PUT,DELETE,POST.
  • Since WebAPI services will not require any configuration they are very easy to consume by any client.
  • Even portable devices like Mobile devices can easily consume WebAPI.lt is the biggest advantages of WebAPI.

Question 46.
How are Requests mapped to Action methods in WebAPI?
Since WebAPI will use HTTP verbs so a client which can consume a WebAPI requires some way to call the WebAPI method.
Client will use HTTP verbs to call the WebAPI action methods.For example to call a method called GetEmployee a client will use a jQuery method as:

$.get("/api/Employees/l", null, function(response) {


Therefore, there is no mention of the method name above.Instead GetEmployee method will be called using the GET HTTP verb.
We define the GetEmployee method as:

public void GetEmployee(int id)

As we will see the GetEmployee method is decorated with the [HttpGet] attribute.We will use different verbs to map the different HTTP requests:

  • HttpGet
  • HttpPost
  • HttpPut
  • HttpDelete

Question 47.
Can the HTTP request will be mapped to action method without using the HTTP attribute ?
There are actually two ways to map the HTTP request for action method.One of the ways is to use the attribute on the action method .There is another way is to just name method starting with the HTTP verb.For example if we required to define a GET method we can define it as:

public void GetEmployee(int id)

The above method will be automatically mapped with the GET request since it can start with GET.

Question 48.
What is the base class of WebAPI controllers?
APIController is the base class from which all WebAPI controller derive Providing an alias to WebAPI action method
By using the ActionName attribute.For example we Can rename the GetEmployee action method as:

 public void GetEmployee(int id)

Question 49.
What types can WebAPI action method return?
WebAPI will return any of the following types:

  • void This means WebAPI will not returns any data.
  • HttpResponseMessage This allows to have control over the response.
  • IHttpActionResult This acts as the factory for creating HttpResponseMessage.
  • Custom type Any custom type.WebAPI uses different Media formatters to serialize custom type.

Question 50.
Can a WebPI return an HTML View?
WebAPI will return data so views will not returned from WebAPl.lf we want to return views then using MVC is better idea.

Question 51.
How can you give a different name to action method ?
We will provide a different name to action methof by using the ActionName attribute.For example if we want to rename a method called GetStudent to search then We can use the ActionName attribute as:

public ActionResult GetStudent(int id)
// get student from the database
 return View();

Question 52.
What is routing in WebAPI?
Routing in WebAPI is used to match URLs with different routes.Routes specify which controller and action can handle the request.Routes will be added to the routing table in the WebApiConfig.es as:

name: “API Default”,
routeTemplate: “api/{controller}/{id}”,
defaults: new {id = RouteParameter.Optional}
Routing mechanism can also be used in MVC.

Question 53.
What is MessageHandler?
Message handler can be used to receive an HTTP request and to return HTTP response.Message handlers will be implemented as classes deriving from HttpMessageHandler.They will implement the cross-cutting concerns.
Question 54.
How WebAPI is useful in creating RESTful web services
REST is stand for ‘Representational State Transfer’.It is an architectural pattern and will use HTTP as the communication meachnism.ln a REST API resources will be the entities
which are represented using different end points.
Question 55.
WebAPI is used for creating RESTful web services?
WebAPI controllers will represent different entities in application and different action methods will be mapped using HTTP verbs like POST and GET.
Question 56.
Will you lose all of your work if you accidentally exit a container?
No, We won’t lose any information, data and other parameters if we accidentally exit the Docker container. The only way to lose progress would be to issue a specific command to delete the container – exiting it won’t do the files within any harm.
Question 57.
Can Web API return view in MVC?
We will not return view from Web API.
Question 58.
How to restrict access to methods with specific HTTP verbs in Web API?
With the help of Attributes such as http verbs one will implement access restrictions in WebAPI.
We will define HTTP verbs as attribute over method for restricting access.
Example :
public void SampleMethod(SampleClass obj)

Question 59.
What is Web API Routing?
Routing is pattern matching such as in MVC.
All routes can get registered in Route Tables.
Example :
Routes. MapHttpRoute(
Name: “SampleWebAPIRoute”,
routeTemplate: “api/{controller}/{id}
defaults: new {id = RouteParameter.Optional}

Question 60.
What are the return types supported in Web API?
A A Web API controller action will return any of the following:
1. void – this type returns will empty content (Status Code :204)
2. HttpResporrseMessage – this can convert response for an HTTP response message.
3. IHttpActionResult – internally calls will ExecuteAsync for creating an HttpResponseMessage.
4. Some other type – we will write the serialized return value into the response body.
Question 61.
What is the namespace for IHttpActionResult return type in Web API?
System.Web.Http.Results namespace
Question 62.
What is the disadvantage of “Other Return Types” in Web API?
The main disadvantage of this approach is that we will not directly return an error code such as 404 error.
Question 63.
What are the default media types supported by Web API?
Web API will support XML, JSON, form-urlencoded data, BSON and also can support additional media types by writing a media formatter.
Question 64.
How do you construct HtmIResponseMessage?
Following is the way for constructing to do,
public class TestController: ApiController
public HttpResponseMessage Get( )
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("Testing", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValueQ
MaxAge = TimeSpan.FromMinutes(20)
return response;

Question 65.
What is the status code for “Emptry return type” in Web API?
void will return empty content and its code is 204.

Question 66.
What is HTTPResponseMessage?
This will represent the response of the WebAPI action method.lt can allow to return the data along with the status code such as success or failure.
In the following example if the passed Roll Number exists in the list of students then the method returns the Student object and the status code “OK” while if the roll number doesn’t exists then “NotFound” status code is returned
public HttpResponseMessage GetStudent(int number)
Student stud = studentList.Where(student => student.rolINo
== number). FirstOrDefault( ) ;
if (stud != null)
return Request.CreateErrorResponse(FlttpStatusCode.NotFound, "Student Not Found");

Question 67.
Is it possible to have MVC kind of routing in Web API?
Yes, we will implement MVC kind of routing in Web API. )

Question 68.
Where is the route is defined in Web API?
Route can be defined in the WebApiConfig.es file, that will be placed in the App_Start directory.
App_Start -> WebApiConfig.es
name: “myroute”,
routeTemplate: “api/{controller}/{id}”,
defaults: new {id = RouteParameter.Optional} ;
); :
Question 69.
Why “api/” segment is used in Web API routing?
It will be used for avoiding collisions with ASP.NET MVC routing
Question 70.
Explain Action Results in WebAPI ?
void : Nothing return
HttpResponseMessage : Convert directly to HTTp Response message
IHttpActionResult: CaH ExecuteAsync for creating artHttpResponseMessage, change to an HTTP response message.
Some other type : Write a serialized return value HttpResponseMessage Example :
public HttpResponseMessage GetData( )
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue( )
MaxAge = TimeSpan.FromMinutes(20)
return response;
public HttpResponseMessage GetData( )
// Get a list of Students from a database.
Enumerable students = GetStudentsFromDB( );

// Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, students);
return response;


It defines an HttpResponseMessage
Simplifies unit testing your controllers.
Moves common logic to create HTTP responses to separate classes.
create the intent of the controller action clearer, to hide the low-level details of
constructing the response.
public class MyResult: IHttpActionResult

string _value;
HttpRequestMessage _request;

public MyResult(string value, HttpRequestMessage request)
_value = value;
_request = request;
public Task ExecuteAsync(CancellationToken cancellationToken)
var response = new HttpResponseMessageQ
Content = new StringContent(_value),
RequestMessage = _request
return Task.FromResult(response);

public class ValuesController: ApiController
public IHttpActionResult Get()
return new MyResult("Pass", Request);

Question 71.
How parmeters gets the value in WebAPI ?
The following way parameters get the values
1) URI
2) Request body
3) Custom Binding

Question 72.
How to enable Attribute routing ?
For enabling attribute routing, call MapHttpAttributeRoutes( ); method in WebApi config file.
public static void Register(HttpConfiguration config)
// Web API routes
config. MapHttpAttributeRoutesQ;
// Other Web API configuration not shown.

Question 73.
Can we apply constraints at route level ?
Yes we will apply.
public User GetStudentByld(int id) {…}

public User GetStudentByName(string name) {…}
The first route can only be selected whenever the “id” segment of the URI is an integer. Otherwise, the second route can be chosen.
Question 74.
How to mention Roles and users using Authorize attribute in Web API?
// Restrict by Name
public class StudentController: ApiController
// Restrict by Role [Authorize(Roles=" Administrators")] public class StudnetController: ApiController

Question 75.
How to enable SSL to ASP.NET web?
To enable SSL to ASP.NET web , click project properties there we will see this option.

Question 76.
How to add certificates to website?
1. go to run type command mmc
2. click on ok
3. its opend certificate add window

Question 77.
Write a LINQ code for authenticate the user?

public static bool Login(string UN, string pwd)
StudentDBEntities students = new StudentDBEntitiesQ
students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) //
students has more than one table

Question 78.
How to navigate other page in JQuery?
using widow.location.href = “~/homw.html”;

Question 79.
Exception handling in WebAPI?
The HttpResponseException most common exception in WebAPI.

public Product GetStudentDetails(int rno)
Student studentinfo = repository.Get(rno);
if (studentinfo == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return studentinfo;

we will handle the exceptions at action method level or controller level using exception filters.

if we required to apply any filter to entire application , register the filter in WebAPI confil file

using Exception hadlers and Exception loogers aslo can handle the Exceptions

Question 80.
What is NonActionAttribute class in WebAPI?
If we required to restrict the particular actionmethod accessing from browser, we will
NonAction attribute.public ActionResult
public ActionResult lnsert(){ return View( );
Above method not getting access from browser

Question 81.
How parameter binding works in Web API?
Following are the rules followed by WebAPI before binding parameters –
1. If it is simple parameters such as bool,int, double etc. then value can be obtained from the URL.
2. Value is read from message body in case of complex types.

Question 82.
Can we do unit test Web API?
Web API will be unit test by using Fiddler tool.
Following is the settings to be updated in Fiddler:
Compose Tab -> Enter Request Pleaders -> Enter the Request Body and execute

API Stands for Application Program Interface. It is a framework that consists of various components of a small software package to interact between the applications or interfaces. Web API is an Application Program Interface used in web applications, The Web API gives lot of flexibility for the developers to build a configurable system, also it enables easy maintenance of system in future. Almost every new application uses API framework in these days.