Sie sind auf Seite 1von 40

What are the possible ways of hosting a WCF service? Explain.

For a Windows Communication Foundation service to host, we need at least a managed process, a
ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:

Hosting in a Managed Application/ Self Hosting

Console Application

Windows Application

Windows Service

Hosting on Web Server

IIS 6.0 (ASP.NET Application supports only HTTP)

Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
NamedPipes, MSMQ.

How we can achieve Operation Overloading while exposing WCF Services?

By default, WSDL doesnt support operation overloading. Overloading behavior can be achieved by using Name
property of OperationContract attribute.
interface IMyCalculator
[OperationContract(Name = SumInt)]
int Sum(int arg1,int arg2);
[OperationContract(Name = SumDouble)]
double Sum(double arg1,double arg2);
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and

What Message Exchange Patterns (MEPs) supported by WCF? Explain each of

them briefly.
Windows Communication Foundation supports the following Message Exchange Patterns (MEPs):


One Way

Its the default pattern. In this pattern, a response message will always be generated to consumer when the
operation is called, even with the void return type. In this scenario (void return type), response will have empty

SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality
but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued
message delivery, OneWay is the only available option.

The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to
initiate some longer-running processing and require a notification back from service in order to confirm that the

requested process has been completed.

Please follow for detailed implementation for Message Exchange Patterns in WCF here.

What is DataContractSerializer and How its different from XmlSerializer?

Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we
are talking about web services, serialization is very important.

Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach
as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out
means you dont have to specify each and every property to serialize, specify only those you dont want to
DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will
be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better
Back to Top

7. What are Contracts in WCF?

A Contract is basically an agreement between the two parties i.e. Service and Client. In WCF, Contracts can be
categorized as behavioral or structural.


Behavioral Contractsdefinethatwhatoperationsclientcanperform on a service.

ServiceContract attribute is used to mark a type as Service contract that contains operations.

OperationContract attributes is used to mark the operations that will be exposed.

Fault Contract defines what errors are raised by the service being exposed.
Structural Contracts

DataContract attribute define types that will be moved between the parties.

MessageContract attribute define the structure of SOAP message.

Please explain briefly different Instance Modes in WCF?

WCF will bind an incoming message request to a particular service instance, so the available modes are:

Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
Per Session: Instance created for a complete session of a user. Session is maintained.
Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of

Please explain different modes of security in WCF? Or Explain the difference between
Transport and Message Level Security.
In Windows Communication Foundation, we can configure to use security at different levels
a. Transport Level security means providing security at the transport layer itself. When dealing with security at
Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the
physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings
have built-in security.
<binding name=netTcpTransportBinding>
<security mode=Transport>
<Transport clientCredentialType=Windows />

b. Message Level Security

For Tranport level security, we actually ensure the transport that is being used should be secured but in message
level security, we actually secure the message. We encrypt the message before transporting it.
<binding name=wsHttpMessageBinding>
<security mode=Message>
<Message clientCredentialType=UserName />
It totally depends upon the requirements but we can use a mixed security mode also as follows:
<binding name=basicHttp>
<security mode=TransportWithMessageCredential>
<Transport />
<Message clientCredentialType=UserName />

Following table further illustrate point by point difference between SOAP-based WCF Service and Web API.

SOAP-based WCF


Multiple Protocol Support.

Limited to HTTP only.

SOAP is the default format. SOAP

Web API renders string (Plain XML or

message has a specific format.

JSON string).

Heavy weight as SOAP message have

Light weight as only required


more than just data.

information is passed.


Follows WS-* specification.

Follows REST principles.



4 simple steps to enable tracing in WCF

By IMRAN ABDUL GHANI | June 7, 2012

Tracing mechanism in Windows Communication Foundation is based on the classes that resides in
System.Diagnostic namespace. Important classes are Trace, TraceSource and TraceListener. For better
understanding we will follow step by step approach in this WCF Tutorial. Following are the steps to enable tracing in

Step 1. Configuring WCF to emit tracing information/Define Trace Source

We have the following options:


In configuration file, we will define a source to enable this configuration as follows:

<source name=System.ServiceModel.MessageLogging>

Step 2. Setting Tracing Level

We have the following available options, we need to set this tracing level to available options other than default








In configuration file, we can choose above values for switchValue attribute as follows:
<source name=System.ServiceModel.MessageLogging

Step 3. Configuring a trace listener

For configuring a trace listener, we will add following to config file.
<add name=messages
initializeData=d:logsmessages.svclog />

Step 4. Enabling message logging

logEntireMessage: By default, only the message header is logged but if we set it to true, entire message including
message header as well as body will be logged.
logMalformedMessages: this option log messages those are rejected by WCF stack at any stage are known as
malformed messages.
logMessagesAtServiceLevel: messages those are about to enter or leave user code.
logMessagesAtTransportLevel: messages those are about to encode or decode.
maxMessagesToLog: maximum quota for messages. Default value is 10000.
maxSizeOfMessageToLog: message size in bytes.
Putting all this together, configuration file will appear like this.
<source name=System.ServiceModel.MessageLogging>
<add name=messagelistener
type=System.Diagnostics.XmlWriterTraceListener initializeData=d:logsmyMessages.svclog></add>
<messageLogging logEntireMessage=true

Note: In this case, information will be buffered and not published to file automatically, So, we can set the autoflush
property of the trace under sources as follows:
autoflush =true />


Explain what is WCF?

WCF (Windows Communication Framework) is Microsoft framework to make inter-process

communication easier. Through various means, it lets you do the communication like MS messaging
Queuing, Services, Remoting and so on. It also allows you talk with other.NET apps, or non-Microsoft
technologies (like J2EE).

Mention what are the main components of WCF?

Main components of WCF are


Service: The working logic

Host: The path where the data is saved. E.g., .exe, process, windows service
Endpoints: The way the service is exposed to the outside world
Explain how does WCF works?

WCF follows the Software as a Service model, where all units of functionality are defined as services.
For communication, each point is a portal or connection either with the client or other services. It is a
program that exposes a collection of endpoints.

Explain what is the difference between ASMX web services and WCF?

The difference between WCF and ASMX or web service is that ASMX is designed to send and
receive messages using SOAP over HTTP only. While the WCF can exchange messages using any
format over any transport protocol
Mention what is the endpoint in WCF and what are the three major points
in WCF?
Every service must have an address that determines where the service is located, contract that
defines what the service does and binding that tells how to communicate with the service.

Address: It specifies the location of the service which will be

like http://Myserver/Myservice. To communicate with our service client it will use this

Contract: It specifies the interface between the server and client. Its a simple
interface with some attribute

Binding: It decides how two parties will communicate with each other in terms of
transport and encoding and protocols


Explain how many types of contract does WCF defines?

WCF defines four types of Contracts


Service Contracts
Data Contracts
Fault Contracts
Message Contracts
What are the transport schemas does WCF supports?

It supports


Peer network
IPC ( Inter Process Communication)
Mention what are the ways of hosting a WCF service?

The ways of hosting a WCF service are



WAS (Windows Activation Service)

Mention the address syntax and the different formats of WCF transport
Address syntax of WCF transport scheme is
[transport]:// [machine or domain] [: optional port] format

In WCF what are duplex contracts?

Duplex messaging or call-back is used in WCF to communicate with the client. Over different transport
system Duplex messaging in WCF is done like TCP, Named pipe and even HTTP. Collectively this is
known as duplex contracts in WCF.

Mention what are the different instance modes in WCF?

To a particular service instance WCF binds an incoming message request, so the available modes are

Per Call: This instance is created for each call, efficient in terms of memory but need
to maintain session

Per Session: For a complete session of a user instance are created

Single: One instance is created which is shared among all the users and shared
among all. In terms of memory it is least efficient.
12) Explain what is a Service Proxy in windows Communication Foundation?
In WCF, a service proxy enables applications to interact with WCF service by sending and receiving
messages. Its a class that covers service details like service path, service implementation technology,
platform and communication protocol and so on. So, when the application interact the service through
proxy, it gives the impression that its communicating a local object.

Explain what is SOA?

SOA (Service Oriented Architectural) is a collection of services that determines how two computing
entities will communicate with each other to achieve certain business functionality and also how one
entity can work on behalf of another entity.

What are the types of Data Contracts in WCF?

There are two types of Data Contracts


Data Contract: Attribute used to define the class

Data Member: Attribute used to define the properties
What are the three types of transaction manager WCF supports?

The types of the transaction manager that WCF supports are

Light Weight

WS- Atomic Transaction

OLE Transaction
16) List out the difference between XMLSerializer and the


For WCF, DataContractSerializer is the default


XMLSerializer is not a default serializer

Compare to XMLSerializer it is faster

XMLSerializer is slower

It is used for simple schemes

It is used for complex schemes


Explain what are the MEPs available in WCF?

MEP stand for Message Exchange Pattern, three types of message exchanged patterns are allowed.

Data Gram
Request and Response


Name the namespace that is used to access WCF service?

System.ServiceModel is used to access WCF service


List out the types of binding available in WCF?

The types of binding available in WCF are


Explain what is DataContractSerializer?

The process of changing an object instance to a portable and transferable format is known as the
Serialization, and serialization of data is referred as DataContractSerializer.

Mention what are the various address format in WCF?

The various address format in WCF are

HTTP Address Format: http:// local host:

TCP Address Format: net.tcp://local host:

MSMQ Address Format:net.msmq://localhost:

22) What is REST and what is the problem with WCF REST and how it can be
REST stands for Representational State Transfer, for designing network application REST is used. It
relies on a stateless, client server, cacheable communications protocol. The reason behind creating
WCF is to support SOA and not REST. It requires a lot of configuration in order to create HTTP REST
service using WCF. To overcome this tedious task, ASP.NET web API was introduced.

List out what are the different isolation levels provided in WCF?

The different isolation levels provided in WCF are

Read Uncommitted
Read Committed
Repeatable Read

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as
HTTP or TCP) and the encoding being used (such as text or binary).
A binding can contain binding elements that specify details like the security mechanisms used to secure
messages, or the message pattern used by an endpoint.
WCF supports nine types of bindings.

1. Basic binding :
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web
service, so that old clients can work with new services. When used by the client, this binding enables
new WCF clients to work with old ASMX services.
2. TCP binding :
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It
supports a variety of features, including reliability, transactions, and security, and is optimized for WCFto-WCF communication. As a result, it requires both the client and the service to use WCF.
3. Peer network binding :
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer networkenabled client and services all subscribe to the same grid and broadcast messages to it.
4. IPC binding :
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine
communication. It is the most secure binding since it cannot accept calls from outside the machine and
it supports a variety of features similar to the TCP binding.
5. Web Service (WS) binding :
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a
variety of features such as reliability, transactions, and security over the Internet.
6. Federated WS binding :
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering
support for federated security.
7. Duplex WS binding :
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports
bidirectional communication from the service to the client.
8. MSMQ binding :
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for
disconnected queued calls.
9. MSMQ integration binding :
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ
messages, and is designed to interoperate with legacy MSMQ clients.

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is
associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
2. TCP
3. Peer network
4. IPC (Inter-Process Communication over named pipes)

The sample address for above transport schema may look like

hat are different isolation levels provided in WCF?

The different isolation levels:
1. READ UNCOMMITTED: An uncommitted transaction can be read. This transaction can be rolled
back later.
2. READ COMMITTED :- Will not read data of a transaction that has not been committed yet
3. REPEATABLE READ: Locks placed on all data and another transaction cannot read.
4. SERIALIZABLE:- Does not allow other transactions to insert or update data until the transaction is
How do I serialize entities using WCF?
LINQ to SQL supports serialization as XML via WCF by generating WCF serialization attributes and
special serialization specific logic during code-generation. You can turn on this feature in the designer
by setting serialization mode to Unidirectional. Note this is not a general solution for serialization as
unidirectional mode may be insufficient for many use cases.

16) Explain Per Call instance mode in WCF?

In Per Call mode, When a request has made to service, new instance of service will be created
for each method call and this will be disposed once the response goes to client.
17) Explain Per Session instance mode in WCF?
Per Session creates a logical session between service and client and it will be maintained till the
session the ends. When client requests from service the session will be created and it is dedicated
to instance for that client and it will going to end when client session ends.
18) Explain Singleton instance mode in WCF?
In Singleton mode all the clients are connected to the single instance of the service and when
service configured for Singleton mode, instance will be created when service is hosted and it will
be disposed once its shuts down.

19) What is Throttling in WCF?

Throttling is used to limit the sessions or instances to be created at application level. And this will
increase the performance.
20) What is the significance of maxConcurrentCalls in Throttling?
This attribute in throttling is used to limit the total number of calls which are going to the service
instances. The default value is 16.
21) What is Service Proxy in WCF?
WCF Proxies are used to enable the communication between client and server by exchanging the
messages in the form of requests and responses. It will have the details like Service Path, Protocol
details and so on.
22) Explain Service Oriented Architecture?
Service Oriented Architecture is known as SOA. It is a design pattern where business functionality
will be as a service and client will communicate to the service using proxy. Advantage of this will be
It is independent of platforms, vendor and product.
4) Mention types of transaction managers in WCF?
Below are the types of transaction managers

WS- Atomic Transaction

Light Weight

OLE Transaction
25) Explain DataContractSerializer ?
DataContractSerializer is introduced in .NET 3.0 and WCF uses DataContractSerializer as default
one. But now this serializer can be used for other serialization purposes also. For serialization
WriteObject() method is used.
Eg: DataContractSerializer dataContractSerializer = new

26) Explain XMLSerializer ?

This serializer was there from the beginning of .NET version. To serialize or deserialize an object
just create an instance of XmlSerializer and pass the type of object. Methods Serialize() or
DeSerialize() methods used to serialize and deserialize objects respectively.
Eg: System.Xml.Serialization.XmlSerializer xmlSerializer = new
29) Explain Request-Reply mode in WCF?
By default WCF works in this mode. When client made a request to a service, client will wait till it
gets the response back to the client. If the response is not received till the given time, timeout error
thrown. If client gets the response then next instructions will be executed.
30) What is the significance of receiveTimeout property in WCF?
This property is used to get/set the time interval that a connection remains active.
31) Explain One-Way mode in WCF?
In this mode client send a request to the server but does not wait till the response comes and does
not care whether the request is failed or succeeded. Client will not blocked in this case till it
receives the response.
32) Explain Callback mode in WCF?
This is the special mode of WCF where WCF on call back calls the method of client and in this
scenario WCF service acts like a client and client acts like a service. But HTTPBinding does not
support this mode we have to switch to WSDualHttpBinding.
33) What are Events in WCF?
Events allow the clients to get notified once its occurred in service side. Events will always result in
direct call from client. Since service firing the event its called the publisher and since client is being
notified about the event it is called subscriber.
37) What is WCF RIA?

This is the framework for developing n-tier application for RIA (Rich Internet App). This is used in
for Rich Internet Apps like Silverlight, AJAX etc. It solves major problems like Tight Coupling.
38) How to generate proxy for WCF?
Proxy can generated from below steps

Using Visual Studio

Using SvcUtil
39) Explain how to generate proxies using Svcutil in WCF?
SvcUtil is a command line utility. We can write the below command to generate proxy
svcutil /t:code http://<mycreatedserviceurl>/out:<file_name>.cs /config:<file_name>.config
40) What you mean by Transport Reliability ?
Transport Reliability meaning the guaranteed delivery of packets over network as protocol TCP
does. It is not only the guaranteed delivery of packets it maintains the order of the packets as well.
41) What are default endpoints in WCF?
If service does not have any endpoints either in config or in program, by default WCF adds up one
endpoint to the service created.
42) How to enable metadata information of the service?
Below are the ways to enable the metadata for WCF

For Default Endpoint - <serviceMetadata> tag is used in web.config file without specifying
the endpoint.

For Custom Endpoint - - <serviceMetadata> tag is used in web.config file with specifying the
defined endpoint.
43) Which bindings are used for metadata configuration in WCF?
Below are the list of bindings that are used for metadata




44) What is the way to test our WCF application without creating client application?
Tool called - wcftestclient.exe used for testing the WCF service without creating a client
application. We can open this tool from visual studio command prompt.
45) How to configure the reliability in configs file?
In config file we can use the tag of reliability as in the below code snippet
<binding name = "MyTestBinding">
<reliableSession enabled = "true"/>

46) Can overload methods in WCF? If Yes, How?

Yes we can overload operations or methods in WCF. Below is the sample code depicts the same
interface IMyTestCalculator

[OperationContract(Name = "AddTestInteger")]
int AddTest(int pararm1,int pararm2);
[OperationContract(Name = "AddTestDouble")]
double AddTest(double pararm1,double pararm2);

47) Explain Known Types in WCF?

If we define the complex complex class as the property of class would give a hard time for the
compiler during deserilization process. So we will use attribute - KnownType to the parent class.
48) Give an example for KnownType?
Please check the below example for KnowTypes
public class TestClassVehicle

public class TestClassCar : TestClassVehicle

public class TestClassTruck : TestClassVehicle

49) Explain ServiceKnownType in WCF?

ServiceKnownType is used at Opeartion/Method level. When serviceknowntype is applied to the
operation then that only operation will use known type.
50) Give an example for ServiceKnownType?
Below is the sample code snippet
public Interface ITestVehicleService

Vehicle AddNewTestVehicle(TestClassVehicle myVehicle);

bool UpdateTestVehicle(TestClassVehicle myTestVehicle);

51) What are Fault Contracts in WCF?

This contract is used to raise the error from service side or in simple words client will come to know
about the service error from fault contract.
52) Write a code snippet for Fault Contract in WCF Service?
Below is the code snippet for fault contract
public Interface ITestVehicleService

Vehicle AddNewTestVehicle(TestClassVehicle myVehicle);

bool UpdateTestVehicle(TestClassVehicle myTestVehicle);

public class VehicleFault

private string vehicle;

private string problemType;

public string Vehicle
get { return vehicle; }
set { vehicle = value; }

public string ProblemType
get { return problemType; }
set { problemType = value; }
53) What are Styles of models WCF supports?
WCF service supports 2 styles of models

RPC style - In RPC-style we can use the serialize types and it provides the feature that are
available for local calls.

Message style - Message style WCF allows the message header to be customized and it
also allows us to define the security for body and header messages.
54) What are Message Contracts in WCF?
Message is the data which is passed from client to server and vice versa. WCF mainly uses SOAP
protocol for sending these messages to and fro. Message Contract can be applied to the class and
MessageHeader and MessageBodyMember attributes are used for custom body and header
included in the message. (class)
55) What are the modes of sessions in WCF?
Below are the list of session modes in WCF



Not Allowed
56) What is Durable Service?
These are WCF services which are used to persist the session state and its information even after
client restarted the service host. It may use SQL for data storing state information.
57) How to implement Durable Services?
Durable services use DurableService attribute which can have attributes CanCreateInstance
and CompletesInstance.
58) Can we have two-way binding for MSMQ?
Yes we can have two-way bindings for MSMQ.
59) Explain dead letter queues?
Queue does not need to have a continuous connection between client and server. Message will be
in queue once client or server puts some data into that and will stay till it has been picked up by
client or server. In case that queue has not been picked within given timestamp then it will expire
and is called dead letter queues.

60) How to track the service users?

Using Parameter Inspector extension we can track WCF service users. We can use methods like
AfterCall and BeforeCall.
61) How we can manage session in WCF?
Below are the ways to maintain the session in WCF

Per Call

Per Session

62) What are the main security features used in WCF?
Below are the features used to address security features




63) What are the difference between transport level and message level security?

Transport Level Security It happens at channel level. WCF uses transport like TCP,
HTTP, MSMQ etc. and each of these transports have its own security features.

Message Level Security Here security is at the message level, while transferring the data
to and from between client and server.
64) What is OData?
OData or Open Data Protocol is used to access the information exposed by data sources like SQL,
Cloud Storage etc. using different clients like browsers, BI, mobile etc.
65) Explain parts on OData?
Below are the main parts of Odata

OData Data Model

OData Protocol

OData Service

OData Client Libraries

66) Can we call WCF service in Jquery?
Yes we can call WCF service in Jquery that is called WCF data service and this can be called from
AJAX call.

ASP.Net Web API Interview Questions

1 Votes
Last Updated: 18 October 2015

Hits: 27441

Top ASP.Net Web API Interview Questions and Answers for freshers and 2-5 year experienced dot net
developers with explanation and examples.

1) What is Web API?

It is a framework which helps us to build/develop HTTP services. So there will a client server
communication using HTTP protocol.
2) What is Representational state transfer or REST?

REST is architectural style, which has defined guidelines for creating services which are scalable.
REST used with HTTP protocol using its verbs GET, POST, PUT and DELETE.
3) Explain Web API Routing?
Routing is the mechanism of pattern matching as we have in MVC. These routes will get registered
in Route Tables. Below is the sample route in Web API
Name: "MyFirstWebAPIRoute",
routeTemplate: api/{controller}/{id}
defaults: new { id = RouteParameter.Optional}

4) List out the differences between WCF and Web API?


It is framework build for building or developing service oriented applications.

WCF can be consumed by clients which can understand XML.

WCF supports protocols like HTTP, TCP, Named Pipes etc.


It is a framework which helps us to build/develop HTTP services

Web API is an open source platform.

It supports most of the MVC features which keep Web API over WCF.

5) What are the advantages of using REST in Web API?

REST always used to make less data transfers between client and server which makes REST an
ideal for using it in mobile apps. Web API supports HTTP protocol thereby it reintroduces the old
way of HTTP verbs for communication.
6) Difference between WCF Rest and Web API?
WCF Rest

WebHttpBinding to be enabled for WCF Rest.

For each method there has to be attributes like WebGet and WebInvoke

For GET and POST verbs respectively.


Unlike WCF Rest we can use full features of HTTP in Web API.

Web API can be hosted in IIS or in application.

7) List out differences between MVC and Web API?

Below are some of the differences between MVC and Web API

MVC is used to create a web app, in which we can build web pages.

For JSON it will return JSONResult from action method.

All requests are mapped to the respective action methods.


This is used to create a service using HTTP verbs.

This returns XML or JSON to client.

All requests are mapped to actions using HTTP verbs.

8) What are the advantages of Web API?

Below are the list of support given by Web API



Content Negotiation

Self Hosting


Model Bindings

9) Can we unit test Web API?

Yes we can unit test Web API.
10) How to unit test Web API?
We can unit test the Web API using Fiddler tool. Below are the settings to be done in Fiddler
Compose Tab -> Enter Request Headers -> Enter the Request Body and execute
11) Can we return view from Web API?
No. We cannot return view from Web API.
12) How we can restrict access to methods with specific HTTP verbs in Web API?
Attribute programming is used for this functionality. Web API will support to restrict access of calling
methods with specific HTTP verbs. We can define HTTP verbs as attribute over method as shown
public void UpdateTestCustomer(Customer c)

13) Can we use Web API with ASP.NET Web Forms?

Yes. We can use Web API with ASP.NET Webforms.
14) List out the steps to be made for Web API to work in Web Forms?
Below are the steps to be followed

Creating new controller for Web API.

Adding routing table to Application_Start method in Global.asax

Make a AJAX call to Web API actions.

15) Explain how to give alias name for action methods in Web API?
Using attribute ActionName we can give alias name for Web API actions. Eg:
public void UpdateTestCustomer(Customer c)
16) What is the difference between MVC Routing and Web API Routing?
There should be atleast one route defined for MVC and Web API to run MVC and Web API
application respectively. In Web API pattern we can find api/ at the beginning which makes it
distinct from MVC routing. In Web API routing action parameter is not mandatory but it can be a
part of routing.
17) Explain Exception Filters?
Exception filters will be executed whenever controller methods (actions) throws an exception which
is unhandled. Exception filters will implement IExceptionFilter interface.

18) Explain about the new features added in Web API 2.0 version?
Below are the list of features introduced in Web API 2.0


Attribute Routing

External Authentication

Web API OData

19) How can we pass multiple complex types in Web API?
Below are the methods to pass the complex types in Web API

Using ArrayList

Newtonsoft JArray
20) Write a code snippet for passing arraylist in Web API?
Below is the code snippet for passing arraylist
ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName = "SmartPhones"};

Product p = new Product { ProductId = 1, Name = "Iphone", Price = 500, CategoryID = 1 };

21) Give an example of Web API Routing?
Below is the sample code snippet to show Web API Routing

name: "MyRoute",//route name
routeTemplate: "api/{controller}/{action}/{id}",//as you can see "api" is at the beginning.
defaults: new { id = RouteParameter.Optional }
22) Give an example of MVC Routing?
Below is the sample code snippet to show MVC Routing
name: "MyRoute", //route name
url: "{controller}/{action}/{id}", //route pattern
defaults: new
controller = "a4academicsController",
action = "a4academicsAction",
id = UrlParameter.Optional
23) How we can handle errors in Web API?
Below are the list of classes which can be used for error handling


Exception Filters

Registering Exception Filters

24) Explain how we can handle error from HttpResponseException?
This returns the HTTP status code what you specify in the constructor. Eg :
public TestClass MyTestAction(int id)
TestClass c = repository.Get(id);
if (c == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return c;
25) How to register Web API exception filters?
Below are the options to register Web API exception filters

From Action

From Controller

Global registration
26) Write a code snippet to register exception filters from action?
Below is the code snippet for registering exception filters from action

public TestCustomer GetMyTestCustomer(int custid)
//Your code goes here
27) Write a code snippet to register exception filters from controller?
Below is the code snippet for registering exception filters from controller
public class TestCustomerController : Controller
//Your code goes here
28) Write a code snippet to register exception filters globally?
Below is the code snippet for registering exception filters globally
GlobalConfiguration.Configuration.Filters.Add( new
29) How to handle error using HttpError?
HttpError will be used to throw the error info in response body. CreateErrorResponse method is
used along with this, which is an extension method defined in HttpRequestMessageExtensions.
30) Write a code snippet to show how we can return 404 error from HttpError?

Below is the code snippet for returning 404 error from HttpError
string message = string.Format("TestCustomer id = {0} not found", customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
31) How to enable tracing in Web API?
To enable tracing place below code in Register method of WebAPIConfig.cs file.
32) Explain how Web API tracing works?
Tracing in Web API done in faade pattern i.e, when tracing for Web API is enabled, Web API will
wrap different parts of request pipeline with classes, which performs trace calls.
33) Can we unit test Web API?
Yes we can unit test Web API.
34) Explain Authentication in Web API?
Web API authentication will happen in host. In case of IIS it uses Http Modules for authentication or
we can write custom Http Modules. When host is used for authentication it used to create principal,
which represent security context of the application.
35) Explain ASP.NET Identity?
This is the new membership system for ASP.NET. This allows to add features of login in our
Below are the list of features supported by ASP.NET Identity in Web API

One ASP.NET Identity System

Persistence Control
36) What are Authentication Filters in Web API?
Authentication Filter will let you set the authentication scheme for actions or controllers. So this way
our application can support various authentication mechanisms.

37) How to set the Authentication filters in Web API?

Authentication filters can be applied at the controller or action level. Decorate attribute
"IdentityBasicAuthentication over controller where we have to set the authentication filter.
38) Explain method AuthenticateAsync in Web API?
AuthenticateAsync method will create IPrincipal and will set on request. Below is the sample
code snippet for AuthenticateAsync
Task AuthenticateAsync(
HttpAuthenticationContext mytestcontext,
CancellationToken mytestcancellationToken
39) How to set the Error Result in Web API?
Below is the sample code to show how to set error result in Web API
HttpResponseMessage myresponse = new
myresponse.RequestMessage = Request;
myresponse.ReasonPhrase = ReasonPhrase;
40) Explain method ChallengeAsync in Web API?
ChallengeAsync method is used to add authentication challenges to response. Below is the
method signature
Task ChallengeAsync(
HttpAuthenticationChallengeContext mytestcontext,

CancellationToken mytestcancellationToken
41) What are media types?
It is also called MIME, which is used to identify the data . In Html, media types is used to describe
message format in the body.
42) List out few media types of HTTP?
Below are the list of media types



43) Explain Media Formatters in Web API?
Media Formatters in Web API can be used to read the CLR object from our HTTP body and Media
formatters are also used for writing CLR objects of message body of HTTP.
44) How to serialize read-only properties?
Read-Only properties can be serialized in Web API by setting the value true to the property
SerializeReadOnlyTypes of class DataContractSerializerSettings.
45) How to get Microsoft JSON date format ?
Use DateFormatHandling property in serializer settings as below
var myjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
myjson.SerializerSettings.DateFormatHandling =

46) How to indent the JSON in web API?

Below is the code snippet to make JSON indenting
var mytestjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
47) How to JSON serialize anonymous and weakly types objects?
Using Newtonsoft.Json.Linq.JObject we can serialize and deserialize weakly typed objects.
48) What is the use of IgnoreDataMember in Web API?
By default if the properties are public then those can be serialized and deserialized, if we does not
want to serialize the property then decorate the property with this attribute.
49) How to write indented XML in Web API?
To write the indented xml set Indent property to true.
50) How to set Per-Type xml serializer?
We can use method SetSerializer. Below is the sample code snippet for using it
var mytestxml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
// Use XmlSerializer for instances of type "Product":
mytestxml.SetSerializer<Product>(new XmlSerializer(typeof(MyTestCustomer)));
51) What is Under-Posting and Over-Posting in Web API?

Under-Posting - When client leaves out some of the properties while binding then its
called under posting.

Over-Posting If the client sends more data than expected in binding then its called overposting.
52) How to handle validation errors in Web API?

Web API will not return error to client automatically on validation failure. So its controllers duty to
check the model state and response to that. We can create a custom action filter for handling the
53) Give an example of creating custom action filter in Web API?
Below is the sample code for creating custom action filter
public class MyCustomModelAttribute : ActionFilterAttribute
public override void OnActionExecuting(HttpActionContext actionContext)
if (actionContext.ModelState.IsValid == false)
//Code goes here
In case validation fails here it returns HTTP response which contains validation errors.
54) How to apply custom action filter in WebAPI.config?
Add a new action filter in Register method as shown public static class WebApiConfig
public static void Register(HttpConfiguration config)

config.Filters.Add(new MyCustomModelAttribute());
// ...
55) How to set the custom action filter in action methods in Web API?
Below is the sample code of action with custom action filter
public class MyCustomerTestController : ApiController
public HttpResponseMessage Post(MyTestCustomer customer)
// ...
56) What is BSON in Web API?
Its is a binary serialization format. BSON stands for Binary JSON. BSON serializes objects to
key-value pair as in JSON. Its light weight and its fast in encode/decode.
57) How to enable BSON in server?
Add BsonMediaTypeFormatter in WebAPI.config as shown below

public static class WebApiConfig

public static void Register(HttpConfiguration config)
config.Formatters.Add(new BsonMediaTypeFormatter());
// Other Web API configuration goes here
58) How parameter binding works in Web API?
Below are the rules followed by WebAPI before binding parameters
If it is simple parameters like bool,int, double etc. then value will be obtained from the


Value read from message body in case of complex types.

59) Why to use FromUri in Web API?

In Web API to read complex types from URL we will use FromUri attribute to the parameter in
action method. Eg:
public MyValuesController : ApiController
public HttpResponseMessage Get([FromUri] MyCustomer c) { ... }
60) Why to use FromBody in Web API?

This attribute is used to force Web API to read the simple type from message body. FromBody
attribute is along with parameter. Eg:
public HttpResponseMessage Post([FromBody] int customerid, [FromBody] string customername)
{ ... }
61) Why to use IValueprovider interface in Web API?
This interface is used to implement custom value provider.