Web Services /WCF / Web API interview questions for experienced

Q)What is Web Service?

The Web Service is a standard software system used for communication between two devices (client and server) over the network. Web services provide a common platform for various applications written in different languages to communicate with each other over the network.
----------------------------------------------------------------------------------------------------------------------------Q)
What are the advantages of web services?

These are some of the important advantages of web services:

Interoperability: With the help of web services, an application can communicate with other applications developed in any language.

Reusability: We can expose the web service so that other applications can use it.

Modularity: With the help of a web service, we can create a service for a specific task such as tax calculation.

A standard protocol for every application program: Web services use standard protocol so that all the client applications written in different languages can understand it. This Standard protocol helps in achieving cross-platform.

Cheaper cost for communication: Web services uses SOAP over HTTP so that anybody can use existing internet for using web services.
It is available over the internet or on intranet networks. It uses a standard XML messaging system
----------------------------------------------------------------------------------------------------------------------------
Q)Explain different types of Web Services?
As I mentioned earlier APIs are few lines of code that take the request from the requester and give back the response in form of data. Now suppose you are creating a utility class where you have written certain methods and can be reused in other different classes. In this case, also we are exchanging data but not making use of any HTTP protocols or networks. Hence, I can term my utility class as an API but not as a Web Service. The most popular Web Service Protocols are

There are basically two types of web services: 

SOAP (Simple Object Access Protocol) Web Services: It is also referred to as transport-independent messaging protocol whose main purpose is to transfer a message, and is based on XML protocol. It is an XML-based protocol for accessing web services.

RESTful (Representational State Transfer) Web Services: It is developed to fulfill the shortcomings of SOAP and to make the web services more effective. It is an architectural style, not a protocol.

SOAP-based Web Service:

Recently I mentioned that web services can be called by any application irrespective of the platform being used to write the code. Now imagine a scenario where this wouldn’t have been possible. So, for every platform, there must be a web service and for every web service managing different code, HTTP or network would result in difficult maintenance.

To enable different applications to use the same web service, there has to be an intermediate language – XML (Extensible Markup Language). Almost every coding platform understands XML. But the drawback is XML doesn’t have any fixed specification across the programming languages. Hence to avoid such a scenario, SOAP protocol was introduced.SOAP is an XML-Based protocol to work over HTTP which has few fixed specifications to be used across all programming languages.SOAP specification is known as SOAP Message. Following are the building blocks in a SOAP Message,

SOAP Envelope: Recognizes where the XML is a SOAP. This element is mandatory.

<?xml version="1.0" encoding="utf-8"?>

<soap envelope xmlns=http://www.google.com>

SOAP Header: Contains header information. For e.g. we need to pass username and password as a mandatory parameter in the request. We can define the same along with the datatypes under the ComplexType tag. See below. This element is optional.

<xsd:complextype>

<xsd:sequence>

<xsd:element name"Username" type="string"/> 

SOAP Body: Contains the web service URL and the elements to be passed with the request, i.e. ComplexType values.

REST-based Web Service

SOAP requires a good amount of bandwidth to exchange data. Due to the complex structure, a small group of developers came up with REST, architectural-based web services, i.e. defined HTTP methods by which two applications can exchange data along with different formats like JSON, XML, Text to exchange data and response code to identify the response status. JSON is the most popular format. Following four HTTP methods are commonly used in REST-based architecture.

GET – to fetch data from the application

POST – if you want to send new data to the application for processing

DELETE – if you wish to remove an existing data

PUT – if you wish to update any existing data

 A REST implementation basically contains the below elements,

 URL – This contains the web service URL.

HTTP Method – Describes what kind of request is the URL all about

Header – this element is used to tell the format in which the response is expected

Request Body – contains the requested web service details. It also contains the data you want to send to the other application.

Response Body – contains the data requested

Response Status code

SOAP

REST

Slower due to defined specification

Faster as there is no defined specifications

Request and response format is always XML

Request and Response can be either in XML, JSON, or plain text.

Requires bandwidth as the amount of data to transfer is a lot

Can work perfectly even in case of low bandwidth

It is a protocol that defines some specifications which are to be followed strictly

Due to its architectural approach, it doesn’t have any strict specification

Less preferred due to its complex design

Easy to implement

Highly secure as it has its own security.

Doesn’t have its own security. Hence depends on application-defined security

HTTP SSL Encryption and WS-Security encryption are used to secure SOAP messages

Data can be secured only by HTTP SSL Encryption

No need for caching mechanism

Requires caching mechanism

Can communicate over HTTP as well as SMTP

Can communicate only over HTTP

Choosing Between SOAP and REST

Use SOAP for,

If your application requires a high level of security

Both consumer and provider should agree to the specification format

Use REST for,

If each operation, i.e. Create, Read, Update, and Delete are independent of each other

If you need to cache any information

The bandwidth is limited


(or)


REST and SOAP are two distinct approaches for building and interacting with web services, differing fundamentally in their nature and implementation.
SOAP (Simple Object Access Protocol)
  • Nature: A protocol. It defines a rigid, standardized messaging format for exchanging structured information.
  • Messaging: Uses XML exclusively. Messages are encapsulated within a SOAP envelope, header, and body.
  • Operations: Function-driven. It exposes specific operations or functions that clients can call.
  • Transport: Can operate over various protocols like HTTP, SMTP, TCP, etc.
  • Complexity: Generally more complex due to its strict protocol definition and XML parsing.
  • Security: Offers built-in security features like WS-Security.
  • Statefulness: Can be stateful, maintaining session information between requests.
Example (SOAP):
To create a new user, a SOAP request might look like this:
Code
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://example.com/UserService">   <soapenv:Header/>   <soapenv:Body>      <ser:CreateUser>         <ser:username>john.doe</ser:username>         <ser:email>john.doe@example.com</ser:email>      </ser:CreateUser>   </soapenv:Body></soapenv:Envelope>
REST (Representational State Transfer)
  • Nature: 
    An architectural style. It provides a set of guidelines for building scalable and stateless web services.
  • Messaging: 
    Flexible and can use various formats like JSON (most common), XML, HTML, plain text.
  • Operations: 
    Data-driven, focusing on resources and using standard HTTP methods (GET, POST, PUT, DELETE) for CRUD operations.
  • Transport: 
    Primarily relies on HTTP.
  • Complexity: 
    Generally simpler and more lightweight due to its statelessness and flexible data formats.
  • Security: 
    Relies on underlying transport security (e.g., HTTPS) and other authentication mechanisms.
  • Statefulness: 
    Stateless, meaning each request from a client to a server must contain all the information needed to understand the request.
Example (REST):
To create a new user, a REST request might involve sending a POST request to a specific URL with a JSON payload:
Code
POST /users HTTP/1.1Content-Type: application/json{  "username": "jane.doe",  "email": "jane.doe@example.com"}
To retrieve user information, a GET request would be sent to a resource URL:
Code
GET /users/jane.doe HTTP/1.1
Key Differences Summarized:

Feature
SOAP
REST
Nature
Protocol
Architectural Style
Messaging
XML only
JSON, XML, HTML, etc. (JSON common)
Operations
Function-driven (e.g., CreateUser)
Data-driven (HTTP methods on resources)
Transport
Various (HTTP, SMTP, TCP)
Primarily HTTP
Complexity
More complex, rigid
Simpler, more flexible
Security
Built-in (WS-Security)
Relies on transport and other mechanisms
State
Can be stateful
Stateless



-----------------------------------------------------------------------------------------------------------------------------

Q)What are the different components of Web Services?

There are various components of web services as given below:

SOAP (Simple Object Access Protocol)

UDDI (Universal Description, Discovery, and Integration)

WSDL (Web Services Description Language)

RDF (Resource Description Framework)

XML (Extensible Markup Language)
-----------------------------------------------------------------------------------------------------------------------------

Q)What is SOA?

Service-Oriented Architecture (SOA) is a style of software design where services are provided to the other components by application components, through a communication protocol over a network. (or)
SOA is an architectural style for building software applications that use services available in a network such as a web. It promotes loose coupling between software components so that they can be reused Services are software components with well-defined interfaces that are implementation-independent. Loosely-coupled services mean services should be independent of each other so that changing one of them should not affect any other services.

There are four Service-oriented principles (tenets) in SOA as given below:

Boundaries are explicit: This SOA principle states that a service can be deployed anywhere and be easily and freely accessed by other services, regardless of the environment or development language of the other services.

Services are autonomous: This SOA principle states that each service must be managed and versioned differently so that they do not affect other services in the process. Contracts, once published, should not be changed. Services need to be isolated and decoupled to accomplish the goal of making them autonomous.

Services share schema and contract, not class: This SOA principle states that services should not pass classes and types; they pass schemas (data) and contracts (behaviors). This allows for a loosely coupled system where the service does not care what type of environment the other service is executing on. The information being passed is 100% platform-independent.

 Service compatibility is determined based on policy: This SOA principle states that each service should have its own compatibility level and knows how it would interact with other services. Services look at each other’s policies, looking for similarities so that they can start communicating. If two services can’t satisfy each other’s policy requirements, they are not compatible with each other.

-----------------------------------------------------------------------------------------------------------------------------
Q) What is SOAP?

The SOAP stands for Simple Object Access Protocol. It is an XML-based protocol for accessing web services. It is platform-independent and language-independent. By using SOAP, you can interact with other programming language applications and also used it for exchanging data in XML-based format over HTTP. SOAP is widely used by web services for exchanging data.

These are some of the important advantages of SOAP web services:

WS Security - SOAP defines its security known as WS Security.

Language-Independent - Its web services can be written in any programming language

Platform Independent - Its web services can be executed on any platform.

Disadvantages of SOAP web services:

Slow - It uses XML format that must be parsed to be read and defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resources.

WSDL Dependent - It uses WSDL and doesn't have any other mechanism to discover the service.

Sample SOAP format:

 <soap:Envelope xmlns:soap=”http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

 <soap:Body xmlns:m="http://www.mysite.com/books">

 <m:Book>

 <m:BookName>WCF and Web Services Interview Questions and Answers</m:BookName>

 </m:Book>

 </soap:Body>

 </soap:Envelope>

 A SOAP message has an optional header and a required body element. A SOAP message header can contain application-specific information like authentication or authorization etc. Also, a SOAP message header must be the first child element of the SOAP Envelope element. The SOAP body element contains the actual SOAP message. Moreover, SOAP is a combination of HTTP protocol and XML i.e. SOAP = HTTP + XML

-----------------------------------------------------------------------------------------------------------------------------Q)What are the main features of SOAP?

The following list specifies the features of SOAP:

SOAP is a communication protocol.

SOAP communicates between applications.

SOAP is a format for sending messages.

SOAP is designed to communicate via the Internet.

SOAP is platform-independent.

SOAP is language-independent.

SOAP is simple and extensible.

SOAP allows you to get around firewalls.

SOAP developed as a W3C standard.
-----------------------------------------------------------------------------------------------------------------------------

What are WS -* Protocols?

The SOAP protocol is used for message exchange between Web Services. But SOAP defines very basic semantics for message headers. It does not always define meaning to the header. Hence to extend SOAP, WS-* protocols specifications have been developed with semantics which can then be reused in various application scenarios.

WS -* protocols are a set of protocols (means standards and specifications) that helps us to implement certain needs and behaviors of a service. These protocols describe how to exchange messages in a secure, transactional, and reliable way by using the headers in the SOAP message. WCF can implement the WS -* protocols by using WsHttpBinding. This binding makes use of some of the WS -* protocols and adds the needed behaviors, such as transactional message calls, reliability, discovery, and addressing.
-----------------------------------------------------------------------------------------------------------------------------

Q) Differences between Asp.net Web Service and WCF?

Asp.net Web Service

WCF

WebService and WebMethod attributes are used for defining web service

ServiceContract and OperationContract attributes are used for defining WCF service.

Supports only HTTP, HTTPS protocols.

Supports various protocols like HTTP, HTTPS, TCP, Named Pipes and MSMQ.

Hosted only in IIS.

Hosted in IIS, WAS (Windows Activation Service), Self-hosting, Windows Service.

Support security but is less secure as compared to WCF.

Supports security, reliable messaging, transaction and AJAX and REST supports.

Supports XML serializer by using System.Xml.Serialization.

Supports DataContract serializer by using System.Runtime.Serialization.

Supports One-Way and Request-Response service operations.

Supports One-Way, Request-Response, and Duplex service operations.

Web Services are slower than WCF

WCF is faster than Web Services.

HashTable cannot be serialized. It can serialize only those collections which implement IEnumerable and ICollection.

HashTable can be serialized.

 

Unhandled Exceptions return to the client as SOAP faults.

Unhandled Exceptions does not return to the client as SOAP faults. WCF supports better exception handling by using FaultContract.

Supports XML and MTOM (Message Transmission Optimization Mechanism) message encoding.

Supports XML, MTOM, Binary message encoding.

1.       Doesn’t support multi-threading.

Supports multi-threading by using ServiceBehaviour class.

-----------------------------------------------------------------------------------------------------------------------------
Q) What is WSDL?

The WSDL stands for Web Services Description Language. It is an XML document containing information about web services such as method name, method parameter. The Client needs a data dictionary that contains information about all the web services with methods names and parameters list to invoke them for the web services. The Web Service Description Language bridge up this gap, by providing all necessary information to the client.

<message>: The message element in WSDL is used to define all different data elements for each operation performed by the web service.

<portType>: The port type element is used to determine the operation which can be performed by the web service. This operation can have two messages one is input and the second one is the output message.

<binding>: This element contains the used protocol.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is UDDI?

The UDDI stands for Universal Description, Discovery, and Integration. It is an XML-based framework for describing, discovering, and integrating web services. It contains a list of available web services. WSDL is part of UDDI.

UDDI is an XML-based framework for describing, discovering, and integrating web services.

UDDI is a directory of web service interfaces described by WSDL, containing information about web services.
-----------------------------------------------------------------------------------------------------------------------------
Q) What is WCF?

WCF stands for Windows Communication Foundation. It is a framework for building, configuring, and deploying network-distributed services.

WCF is a programming model for building and developing service-oriented applications. WCF allows applications to communicate with each other in a distributed environment. WCF is a set of technologies that covers ASMX web services, Web Services Enhancements (WSE), .NET Remoting, and MSMQ. The purpose of WCF is to provide a single programming model that can be used to create services on the .NET platform for organizations.

WCF ABC stands for Address, Binding, and Contract.

Address (Where)

WCF Address specifies a specific location, where the service is hosted. A WCF Address is specified as a URI. URI’s first part specifies the transport protocol (HTTP, TCP, Net.pipe, and MSMQ), and the other parts specify the host machine address and service path as shown in below fig.

http://www.mywebsite/MyService

HTTP->Transport

www. my website->Hosting server Address

MyService-> Service Path

Other sample Addresses are given below:

 http://www.mywebsite/MyService

 net.tcp://www.my website/MyService

 net.pipe://www.my website/MyPipeService

 net.msmq://www.my website/MyMsMqService

Binding (How)

WCF binding specifies how the service and client will communicate with each other in terms of transport protocols and encoding (such as text or binary). WCF binding is a set of binding elements and each element specify, how the service and client will communicate with each other. Each binding must have at least one transport element and one message encoding element.

Contract (What)

WCF contract specifies what the service contains. WCF has five types of contracts: service contract, operation contract, data contract, message contract, and fault contract. Each contract defines certain behavior.
-----------------------------------------------------------------------------------------------------------------------------

Q) How to define multiple endpoints for a WCF service?

A WCF service configuration with multiple endpoints is given below:

 <system.serviceModel>

 <services >

 <service name = "MyWCFService">

 <endpoint address = "http://localhost:90/MyWCFService"

 binding = "wsHttpBinding" contract = "IMyWCFContract"/>

 <endpoint address = "net.tcp://localhost:91/MyWCFService"

 binding = "netTcpBinding" contract = "IMyWCFContract"/>

 </service>

 </services>

 </system.serviceModel>
-----------------------------------------------------------------------------------------------------------------------------

Q)What are default Endpoints?

WCF offers some default endpoints to the service if a service host doesn’t define any endpoints but has at least one base address. For example, WCF uses the basic binding for the HTTP address.

Standard Endpoints:

WCF provides a set of pre-defined endpoints known as Standard Endpoints for metadata exchange, discovery, and web. You can configure the standard endpoints by using a config file and programmatically. Here is the list of standard endpoints :

MEX endpoint

webHttpEndpoint

webScriptEndpoint

workflowControlEndpoint

announcement endpoints

discoveryEndpoint

udpAnnouncementEndpoint

udpDiscoveryEndpoint
-----------------------------------------------------------------------------------------------------------------------------

WCF Hosting:

 WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.

IIS hosting

Self hosting

Windows Activation Service

Windows Service

Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.

IIS 5/6 Hosting

The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol.

Self Hosting

In web service, we can host the service only in IIS, but WCF provides the user to host the service in any application (e.g. console application, Windows form etc.). Very interestingly developer is responsible for providing and managing the life cycle of the host process. Service can also be in-pro i.e. client and service in the same process. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'ClientBase' abstract class.

Note: Host process must be running before the client calls the service, which typically means you have to prelaunch it.

Windows Activation Service

Windows Activation service is a system service available with Windows vista and windows server 2008. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately.Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps

Enable WCF for non-http protocols

Create WAS hosted service

Enable different binding to the hosted service

Windows Service Hosting

In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.

The service will be hosted, when system starts Process life time of the service can be controlled by Service Control Manager for windows service.All versions of Windows will support hosting WCF service.

-----------------------------------------------------------------------------------------------------------------------------

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
  • Serializable

 ----------------------------------------------------------------------------------------------------------------------------

Q) What are the different WCF contracts?

WCF contract specifies the service and its operations. WCF has five types of contracts:

Service contract
Operation contract
Data contract
Message contract
Fault contract

WCF contract specifies the service and its operations. WCF has five types of contracts: service contract, operation contract, data contract, message contract, and fault contract.

Service Contract:

A service contract defines the operations which are exposed by the service to the outside world. A service contract is the interface of the WCF service and it tells the outside world what the service can do. It may have service-level settings, such as the name of the service and namespace for the service.

[ServiceContract]

interface IMyContract

{

 [OperationContract]

 string MyMethod();

}

class MyService: IMyContract

{

 public string MyMethod()

 {

 return "Hello World";

 }

}

Operation Contract:

An operation contract is defined within a service contract. It defines the parameters and returns the type of operation. An operation contract can also define operation-level settings, like the transaction flow of the operation, the directions of the operation (one-way, two-way, or both ways), and the fault contract of the operation.

[ServiceContract]

 interface IMyContract

 {

 [FaultContract(typeof(MyFaultContract))]

 [OperationContract]

 string MyMethod();

 }

Data Contract:

A data contract defines the data type of the information that will be exchanged between the client and the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements.

[DataContract]

class Person

{

 [DataMember]

 public string ID;

 [DataMember]

 public string Name;

}

[ServiceContract]

interface IMyContract

{

 [OperationContract]

 Person GetPerson(int ID);

}

Message Contract:

When an operation contract is required to pass a message as a parameter or return value as a message, the type of this message will be defined as a message contract. A message contract defines the elements of the message (like Message Header, Message Body), as well as the message-related settings, such as the level of message security.

Message contracts give you complete control over the content of the SOAP header, as well as the structure of the SOAP body.

[ServiceContract]

public interface IRentalService

{

 [OperationContract]

 double CalPrice(PriceCalculate request);

}

[MessageContract]

public class PriceCalculate

{

 [MessageHeader]

 public MyHeader SoapHeader { get; set; }

 [MessageBodyMember]

 public PriceCal PriceCalculation { get; set; }

}

[DataContract]

public class MyHeader

{

 [DataMember]

 public string UserID { get; set; }

}

[DataContract]

public class PriceCal

{

 [DataMember]

 public DateTime PickupDateTime { get; set; }

 [DataMember]

 public DateTime ReturnDateTime { get; set; }

 [DataMember]

 public string PickupLocation { get; set; }

 [DataMember]

 public string ReturnLocation { get; set; }

 }

Fault Contract:

A fault contract defines errors raised by the service, and how the service handles and propagates errors to its clients. An operation contract can have zero or more fault contracts associated with it.

[ServiceContract]

interface IMyContract

{

 [FaultContract(typeof(MyFaultContract1))]

 [FaultContract(typeof(MyFaultContract2))]

 [OperationContract]

 string MyMethod();

 [OperationContract]

 string MyShow();

 }

-----------------------------------------------------------------------------------------------------------------------------Q) What are the various ways of hosting a WCF service?

There are four ways of hosting a WCF service.

Self-Hosting
Windows services hosting
IIS hosting
Windows Activation Services hosting (WAS)
-----------------------------------------------------------------------------------------------------------------------------
Q) What is Binding?

WCF binding specifies how the service and client will communicate with each other in terms of transport protocols and encoding (such as text or binary). WCF binding is a set of binding elements and each element specify, how the service and client will communicate with each other. Each binding must have at least one transport element and one message encoding element.

Different types of bindings in WCF:

WCF supports the following types of built-in bindings:

Basic binding

Web binding

Web Service (WS) binding

WS Dual binding

TCP binding

IPC binding

MSMQ binding

Federated WS binding

Peer Network binding

MSMQ integration binding

Basic Binding:

This binding is provided by the BasicHttpBinding class. It is designed to expose a WCF service as an ASMX web service, so that old clients (who are still using ASMX web service) can consume new services. By default, it uses HTTP protocol for transport and encodes the message in UTF - 8 text format. You can also use HTTPS with this binding.

Web Binding:

This binding is provided by the WebHttpBinding class. It is designed to expose WCF services as HTTP requests by using HTTP-GET, HTTP-POST. It is used with REST-based services which may give output as an XML or JSON format. This is very much used with social networks for implementing a syndication feed.

Web Service (WS) Binding:

This binding is provided by the WSHttpBinding class. It is like Basic binding and uses Http or Https protocols for transport. But this is designed to offer various WS - * specifications such as WS – Reliable Messaging, WS - Transactions, WS - Security and so on which are not supported by Basic binding.

wsHttpBinding= basicHttpBinding + WS-* specification

WS Dual Binding:

This binding is provided by the WsDualHttpBinding class. It is like as wsHttpBinding except it supports bi-directional communication means both clients and services can send and receive messages.

TCP Binding:

This binding is provided by the NetTcpBinding class. It uses TCP protocol for communication between two machines within the intranet (which means the same network). It encodes the message in binary format. This is faster and more reliable binding as compared to the HTTP protocol bindings. It is only used when communication is WCF - to – WCF means both client and service should have WCF.

IPC Binding:

This binding is provided by the NetNamedPipeBinding class. It uses a named pipe for communication between two services on the same machine. This is the most secure and fastest binding among all the bindings.

MSMQ Binding:

This binding is provided by the NetMsmqBinding class. It uses MSMQ for transport and offers support to disconnected message queued. It provides solutions for disconnected scenarios in which the service processes the message at a different time than the client sends the messages.

Federated WS Binding:

This binding is provided by the WSFederationHttpBinding class. It is a specialized form of WS binding and provides support to federated security.

 Peer Network Binding:

This binding is provided by the NetPeerTcpBinding class. It uses TCP protocol but uses peer networking as transport. In this networking, each machine (node) acts as a client and a server to the other nodes. This is used in file-sharing systems like torrents.

MSMQ Integration Binding:

This binding is provided by the MsmqIntegrationBinding class. These binding offers support to communicate with existing systems that communicate via MSMQ.

Binding

Protocol/Transport

Message Encoding

Security

Default Session

 

Transaction

Duplex

BasicHttpBinding

Http, Https

Text

None

No

-

-

WSHttpBinding

Http, Https

Text

Message

Optional

Yes

-

WSDualHttpBinding

Http, Https

Text

Message

Yes

 

Yes

Yes

NetTcpBinding

TCP

Binary

Transport

Optional

Yes

Yes

NetNamedPipeBinding

Named Pipe

Binary

Transport

Yes

Yes

Yes

NetMsmqBinding

MSMQ

Binary

Transport

Yes

Yes

No

WSFederationHttpBinding

Http, Https

Text

Message

Yes

Yes

No

NetPeerTcpBinding

P2P

Binary

Transport

-

-

Yes

MsmqIntegrationBinding

MSMQ

Not Supported

Transport

Yes

Yes

-

-----------------------------------------------------------------------------------------------------------------------------

 Q) What are the ways to create a WCF Client?

There are two ways to create a WCF Client or calling a WCF Service:

WCF Proxy

Channel factory

WCF Proxy:

A WCF proxy is a CLR class that exposes the service contract. A Service proxy class has the service contract operations and some additional operations for managing the proxy life cycle and the connection to the service.

There are two ways to create a WCF proxy as given below:

Using Visual Studio by adding a service reference to the client application.

Using SvcUtil.exe command-line utility.

Channel Factory:

A channel factory creates channels of different types that are used by clients to send messages to the service. Channel Factory class is used with a known interface to create the channel. This approach is commonly used when you have access control to both the server and the client.

WSHttpBinding binding = new WSHttpBinding();

EndpointAddress endpoint = new EndpointAddress("http://localhost/WcfService/MyService.svc/ws");

ChannelFactory<IMyService>channelFactory = new ChannelFactory<IMyService>(binding,endpoint );

IMyService channel = channelFactory.CreateChannel();

//calling service operation

channel.DoWork();

//Close channel

channelFactory.Close();

Proxy

Channel Factory

 

Only requires the service URL to access the service.

Requires direct access to the assembly which contains the service contract i.e. must have information about service interface.

Simple and easy to understand

Not easy since channels are complex and network-related

Proxy is best when your service is used by several applications.

Channel Factory is best when your service is tightly bound to a single application

The proxy can be created by using Visual Studio or the SVCUtil tool.

ChannelFactory class is used to create channels and for accessing the service.

-----------------------------------------------------------------------------------------------------------------------------

Q)Message Exchange Patterns (MEP) in WCF?

Message Exchange Patterns describe the way of communication between Client and Server means how client and server would be exchange messages to each other. There are three types of message exchange patterns

Request-Reply:

In this communication, the client sends the message to the service and waits for a reply from the service. Within a ReceiveTimeout period (default timeout is one minute), if the service doesn't respond to the client then the client will receive a TimeoutException. In this pattern, the client waits for the reply message, even if the service operation's return type is void.



This is the by default message exchange pattern in WCF. All WCF bindings except MSMQ-based bindings support this pattern.

[ServiceContract]

public interface RequestReplyService

{

 [OperationContract]

 string GetData(int value);

 [OperationContract(IsOneWay = false)]

 void SaveData(string value);

}

To define this pattern, you can set the IsOneWay property to false explicitly, but by default it is false. So there is a need to define the ISOneWay property for the Request-Reply pattern. A Request-Reply operation returns a header with an HTTP status code of 200 (OK) and a full SOAP response in the message body.

One-Way:

In this communication, the client sends the message to the service and doesn't wait for a reply from the service. In this pattern, the receiver doesn’t send any response to the sender, even if any error occurs in the communication.


This pattern doesn’t support output parameters, by-reference parameters, and return value to an operation, otherwise, you will receive an InvalidOperationException.

All of the WCF bindings support one-way operations. 

[ServiceContract]

public interface OneWayService

{

 [OperationContract(IsOneWay = true)]

 void SaveData(string value);

}

A One-Way operation returns only a header with an HTTP status code of 202 (Accepted) without a message body. This pattern is commonly used with per-call or singleton services only.

Duplex:

In this communication, client and services can send messages to each other by using One-way or request-reply messaging.



Only bidirectional-capable bindings support this pattern like WS Dual, TCP, and IPC bindings.

To make a duplex contract, you must also define a callback contract and assign the type of that callback contract to the CallbackContract property of your service contract’s ServiceContract attribute as shown below example.

[ServiceContract(CallbackContract = typeof(DuplexServiceCallback))]

public interface DuplexService

{

 [OperationContract(IsOneWay = true)] //One-Way

 void SaveData();

 [OperationContract] //Request-Reply.

 string GetData();

 }

 public interface DuplexServiceCallback

 {

 [OperationContract(IsOneWay = true)]

 void Progress(string status);

 }

For this pattern, you must also specified the binding as wsDualHttpBinding with in your web.config as shown below-

<services>

 <service name="WCFServiceApp.DuplexService">

 <endpoint address ="" binding="wsDualHttpBinding" con-tract="WCFServiceApp.IDuplexService">

 </endpoint>

 </service>

</services>
-----------------------------------------------------------------------------------------------------------------------------

Q) Security in WCF?

As WCF supports various protocols i.e. TCP, HTTP, and MSMQ, the user must be sure enough to take necessary steps to guard your message and also must establish security policies for protecting messages and for authenticating and authorizing calls. WCF provides a very easy and rich configurable environment to implement security.

WCF supports the following securities:

Message

Transport

TransportWithMessageCredential

Message Security:

Message security uses the WS-Security specification to secure messages. The message is encrypted using the certificate and can now safely travel over any port using plain HTTP. It provides end-to-end security. Because message security directly encrypts and signs the message, having intermediaries does not break the security. Message security can be used when the client is deployed on the internet.

Transport Security

Transport security is a protocol implemented security so it works only point to point. As security is dependent on protocol, it has limited security support and is bounded to the protocol security limitations. Typically, you can use transport security when your client is deployed within an intranet, as it provides point-to-point security and better performance compared to message security.

TransportWithMessageCredential

This we can call a mixture of both Message and Transport security implementation. Credentials are passed with the message and message protection and server authentication are provided by the transport layer.

Message Security Vs Transport Security

Message Security

Transport Security

Not a good option

The best one for Intranet

Secure if the message is forwarded via intermediate routers

The best way, If there are no intermediate routers between

Provides end to end security

Security provides only for the channel, once the message is out of the transport medium message is unsecured

No Dependency with any protocol

Security inherent from the protocol, so no extra coding

The performance will be slow since every single message is encrypted

Good in Performance

 ----------------------------------------------------------------------------------------------------------------------------

Q) Authentication and authorization in WCF?

Authentication:

Client Authentication

Server Authentication

Mutual Authentication

Client Authentication is authentication by the service to validate and verify that you are the right person to utilize my service methods. Then what is server authentication? Server authentication is authenticated by the client to confirm that the client is talking to the right person, so the client needs to verify the service identity. Why does the client need to verify the server? Because we need to prevent phishing attacks that are nothing but an attacker who makes available a fake service with the same signature as the original one to capture sensitive information about the user, for example, credit card numbers, credit card pins, and transaction passwords are normally not provided to anyone, right? Until the person is your family member or a known good friend. The final one to discuss here is Mutual authentication, which is a combination of client authentication and the server authentication. The client and the server authenticate each other before any operation is made.

Authorization:

Authorization normally decides what are all the system resources or the operations can be accessed by an authenticated user. WCF provides a couple of mechanisms to Implement the authorizations in the services.

Role-Based Authorization:

A claim based Authorization and the Authorization context

I am not going to explain in detail the mechanisms in this article, we will discuss it in my series of articles on WCF Security.

Message Integrity:

It ensures that the contents of the message has not been tampered with or altered in transit. Say for example the customer requests some amount from the bank, what if someone in the middle attacks the message by making some change in the values.

The integrity of data in transit is generally based on cryptographic techniques such as digital signatures.

Message Confidentiality:

It ensures that the data in the message is highly confidential and private and is not read by unauthorized parties. It should not be seen by anyone in the network. Whereas the message integrity is the message would not be altered in the network. Without the message confidentially you cannot achieve the message integrity and vice versa. Message confidentiality is based on cryptographic techniques like data encryption.
-----------------------------------------------------------------------------------------------------------------------------

Q) What is Instance Management in WCF?

WCF manages the session by creating the instance of the service class. This created instance(s) to handle the incoming service request. In WCF, the session is the way of managing the services instance(s) so that the server can use these instances in an optimized way. On the server-side, the InstanceContext class is used to manage the service class instances. There are the following instance management ways :

WCF manages the session by creating the instance of the service class. These created instances (s) handle the incoming service request. In WCF, the session is the way of managing the services instance(s) so that server can use these instances in an optimized way. On the server side, the InstanceContext class is used to manage the service class instances.

In WCF, there are three Instance Management ways as given below:

Per Call

Per Session

Single

Per Call

In this way, each request is served by a new service instance. It means a new service instance is created for each request and destroyed after the request is served. This makes your WCF service stateless means you can’t maintain states between WCF calls.



Per Session

In this way, each and every client request are served by a new single service instance. It means a new service instance is created for a client all requests and destroyed after the client finished its activity.



Single

In this way, all clients’ requests are served by a single service instance. It means a single service instance is created to handle all the clients’ requests and never destroyed after serving the request.This makes your WCF service data shared globally.



How WCF Session is different from Asp.Net Session?

WCF Session management is different from Asp.Net Session Management in the following ways:

WCF Sessions are created and terminated by the service clients.

Server use sessions to manage service instances, not to store some general data like Asp.Net.

WCF Session does not mainly rely on Session ID like Asp.Net, a particular field within the header or body of a group of messages can also be considered as a part of the session.

There may be different Session IDs on the client and server-side, unlike Asp.Net.

-----------------------------------------------------------------------------------------------------------------------------

Q) What is Concurrency Management in WCF?

Concurrency management is closely related to Instance management in WCF but both are two different things. Instance management specifies how the service instances are created while Concurrency management specifies how many concurrent requests are handled by the service instances. By using concurrency, you can make your service instance thread-safe. By default, a per-call service instance is thread-safe since each request is served by a new service instance. A per-session service instance is not thread-safe since multiple requests of a client are served by a single service instance. Hence, it’s required concurrency management. A single service instance is not thread-safe since multiple requests of all clients are served by a single service instance. Hence, it’s required concurrency management.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Impersonation?

Impersonation is a way to authorize a caller (client) identity to access the service domain’s resources. The service resources may be local files or database tables and should be on the same machine on which the service is hosted. By default, impersonation is disabled and resources are accessed by using the WCF service's process identity.
-----------------------------------------------------------------------------------------------------------------------------


Q)What is service versioning?

After the initial deployment of the WCF service, you may need to change the service for a variety of reasons like changing business needs or fixing other issues. Each change in your existing service introduces a new version of the service. Service versioning is helpful in backward compatibility with your existing clients.
-----------------------------------------------------------------------------------------------------------------------------


Q)What is WCF Data Service?

WCF Data Services uses OData (Open Data Protocol) protocol for querying or manipulating the data. WCF Data Services is built on top of WCF REST Services. It is a RESTful service to support CRUD operations on the database using the HTTP protocol. It supports all database operations using URI. DATA protocol can expose data from the relational database, File systems, Web sites, services, etc. It supports XML or JSON format for exposing the data.
-----------------------------------------------------------------------------------------------------------------------------


Q)What are RESTful web services?

The REST stands for Representational State Transfer. It is an architectural style. It is not a protocol like SOAP.

Important advantages of RESTful web services:

Fast - Web Services are fast because there is no strict specification of SOAP. It consumes less bandwidth and resources.

Language-Independent - The web services can be written in any programming language.

Platform Independent - Web services can be executed on any platform.

Can use SOAP - The web services can use SOAP web services as the implementation.

Allows different data formats - The web service permits different data formats such as Plain Text, HTML, XML, and JSON.
-----------------------------------------------------------------------------------------------------------------------------

Q)Name the tools that are used to test web services.

There are various tools used to test web service as given below:
SoapUI
Postman
REST client
JMeter
-----------------------------------------------------------------------------------------------------------------------------

Q)What's the importance of security in web services?

Security is considered a very important feature in any web application. It is essential in web services so that we can make confidential or sensitive information and transactions more reliable. In web services, the security is attained through SSL (Service Socket Layer) that helps in developing EST (Entrust Secure Transaction) platform.
-----------------------------------------------------------------------------------------------------------------------------
Q)What is the importance of URI in REST-based web services?

In REST-based web services, URI (Uniform Resource Locator) is generally used to locate resources on the server that is hosting the web service. Each resource in service will have at least one URI that is used to identify it. Web services clients generally use URI to access the resource. Its format is given below:

<protocol>://<service-name>/<ResourceType>/<ResourceID>
-----------------------------------------------------------------------------------------------------------------------------
Q)Name three primary security issues of Web Services?

The three primary security issues of web services include:

Confidentiality
Authentication
Network Security
-----------------------------------------------------------------------------------------------------------------------------

Q)Name HTTP methods that can be used with RESTful web services.

Some of the HTTP methods that can be used with RESTful web services include:

GET: Used to get and read a resource.

POST: Used to create a new resource.

PUT: Used to update existing resources.

DELETE: Used to delete the resource.

PATCH: Used to apply partial modifications to a resource.
-----------------------------------------------------------------------------------------------------------------------------
Q)What are the written status codes for REST API?

REST API generally returns the following status codes in HTTP response:

200 OK

201 Created

202 Accepted

302 Found

400 Bad Request

401 Unauthorized

404 Not Found

405 Method Not Allowed

409 Conflict

500 Internal Server Error
-----------------------------------------------------------------------------------------------------------------------------
Q)What are .NET Web services and .NET Remoting? Write the difference between them.

.NET Remoting: It is a method that enables objects to communicate or interact with each other across application domains, processes, and machine boundaries, whether application components are present in one computer or different computers across the entire world.

.NET Web service: It is a method that enables cross-platform integration by using XML, HTTP, and SOAP for communication among two devices over WWW. It simply shares business logic, processes, and data through programmatic interfaces across a network.

Web Services

.NET Remoting

It uses HTTP protocol. 

It uses TCP/HTTP/SMTP protocol. 

Its performance is slow as compared to .NET Remoting. 

It provides faster communication and performance when one uses the TCP channel and the binary formatter. 

These services are hosted using IIS and therefore, are more reliable. 

It is less reliable as compared to .NET Web services. 

It supports the XML Schema type system and provides a very simple programming model along with broad cross-platform reach.

It supports a runtime type system and provides a complex programming model along with very limited reach. 

-----------------------------------------------------------------------------------------------------------------------------

Q) Difference between WCF and Web API and WCF REST and Web Service

Web Service:

1.      It is based on SOAP and return data in XML form.

2.      It supports only HTTP protocol.

3.      It is not open source but can be consumed by any client that understands XML.

4.      It can be hosted only on IIS.

WCF:

1.      It is also based on SOAP and return data in XML form.

2.   It is the evolution of the web service(ASMX) and supports various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.

3.      The main issue with WCF is its tedious and extensive configuration.

4.      It is not open source but can be consumed by any client that understands XML.

5.      It can be hosted within the application or on IIS or using Windows service.

WCF Rest:

1.      To use WCF as a WCF Rest service you have to enable webHttpBindings.

2.      It supports HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

3.      To enable other HTTP verbs you have to do some configuration in IIS to accept requests of that particular verb on .svc files

4.      Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

5.      It supports XML, JSON, and ATOM data formats.

Web API:

1.      This is the new framework for building HTTP services in an easy and simple way.

2.  Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

3.      Unlike the WCF Rest service, it uses the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

4.      It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

5.      It can be hosted within the application or on IIS.

6.      It is lightweight architecture and good for devices that have limited bandwidth like smartphones.

7.      Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML, or whatever format you want to add as a MediaTypeFormatter.

 

To Whom Choose Between WCF or WEB API:

1.      Choose WCF when you want to create a service that should support special scenarios such as one-way messaging, message queues, duplex communication, etc.

2.      Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

3.      Choose Web API when you want to create a resource-oriented service over HTTP that can use the full features of HTTP (like Uris, request/response headers, caching, versioning, various content formats).

4.      Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iPhone's, and tablets.





---------------------------------------------------------------------------------------------------------------------------

Two prominent contenders you have when designing the service layer in .Net are WCF and Web

API.WCF is a development platform for SOA -- it provides many features and supports many

different transport protocols. While WCF is a unified framework for building service-oriented

applications, Web API is a lightweight alternative to build RESTful services that can be

consumed by many different clients. RESTful services use basic HTTP and are simple with

much less payload compared to SOAP services. You can use the WebHttpBinding in WCF to

build non-SOAP RESTful services over HTTP. WCF is much more versatile in the sense that it

can support many transport protocols -- HTTP, TCP, etc. You can leverage WCF to build secure,

reliable, and transactional services that can support messaging, duplex communication, and fast

transport channels like, TCP, Named Pipes, or UDP.

If you need to build lightweight, resource-oriented services over HTTP that can leverage the full

features of the HTTP protocol, use versioning, cache control for browsers, and concurrency

using Etags, Web API is a good choice. You should choose Web API over WCF in your service

layer when you would want to expose your services to a broad range of clients i.e., Web

browsers, mobiles, tablets, etc. Web API is lightweight and is well suited on devices that have

limited bandwidth like smartphones. One of the major constraints I faced while using WCF is its

extensive configuration - Web API is much simpler and easy to use. I admit that WCF is much

more versatile compared to Web API but, if you don't need the features that WCF provides and

all you need is just RESTful services over HTTP, I would always prefer Web API as it is

lightweight and simple to use.

I would also like to present a discussion on the differences between Web API and ASP.Net MVC

as there are certain misconceptions on when to choose one over the other. The choice between

ASP.Net MVC and Web API depend on many factors. There are certain considerations you

would need to keep in mind before you decide to use any one of them.

Note that Web API uses HTTP verbs and hence HTTP verb-based mapping for mapping methods

to respective routes. You cannot have overloaded methods for the same HTTP verb for a

particular route. You should be aware of this design constraint (though workarounds are

available) when choosing between ASP.Net MVC and Web API. Unlike ASP.Net MVC, Web

API uses routing based on HTTP verbs rather than URIs that contain actions. So, you can use

Web API to write RESTful services that can leverage the HTTP protocol -- you can design

services that are easier to test and maintain. Routing in Web API is much simpler and you can

leverage content negotiation seamlessly. The routing model in ASP.Net MVC includes actions in

the URIs.

Another point you would want to consider is whether you would like your functionality to be

exposed for a specific application or whether the functionality should be generic. If you want to

expose your services specific to one application only, you would want to use ASP.Net MVC --

the controller in an ASP.Net MVC application is application-specific. On the contrary, you

would want a Web API approach if your business needs require you to expose the functionality

generically. I would prefer to use the Web API approach if the functionality is more data-centric

and the ASP.Net MVC approach if the functionality is more UI-centric.

 You should use Web API over ASP.Net MVC if you would want your controller to return data in

multiple formats like JSON, XML, etc. Also, specifying the data format in Web API is simple

and easy to configure. Web API also scores over ASP.Net MVC in its ability to be self-hosted

(similar to WCF). You would need ASP.Net MVC controllers to be hosted in the same

web server where the application has been hosted because the ASP.Net MVC controllers are part

of the same application. On the contrary, you can host your Web API controllers outside of IIS

also -- you can host it in a lightweight custom host and allow the service to be consumed by

many different clients.



-----------------------------------------------------------------------------------------------------------------------------

 Q) Difference between ASP.NET MVC and ASP.NET Web API?

While developing your web application using MVC, many developers got confused when to use Web API, since the MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In the previous article, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over other services.

Asp.Net Web API VS Asp.Net MVC:

Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view.

Web API helps to build REST-ful services over the .NET Framework and it also supports content negotiation (it's about deciding the best response format data that could be acceptable by the client. it could be JSON, XML, ATOM, or other formatted data), self-hosting which are not in MVC.

Web API also takes care of returning data in particular formats like JSON, XML, or any other based upon the Accept header in the request and you don't worry about that. MVC only returns data in JSON format using JsonResult.

In Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.

Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing, and other MVC features that exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these features exist within.System.Web.MVC Hence Web API can also be used with Asp.Net and as a stand-alone service layer.

You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML, or any other format, and building a full-blown HTTP service. Typically, this will be called Web API self-hosting.

When you have mixed MVC and Web API controllers and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since both are different.

Moreover, Web API is lightweight architecture and except for the web application, it can also be used with smartphone apps.
---------------------------------------------------------------------------------------------------------------------------

Q)What is WebAPI and when to use it?

ASP.NET Web API is a framework for building HTTP services that can be consumed by a broad range of clients including browsers, mobiles, iPhone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection.

ASP.NET Web API is an extension of WCF REST API. In short, it is an replacement of WCF REST API. It can be used with ASP.NET MVC and other types of Web applications like ASP.NET Web Forms. Also, Web API can be used as an stand-alone Web services application.
-----------------------------------------------------------------------------------------------------------------------------

Q)Exception Handling in WCF Service

.NET provides a very simple way of dealing with exceptions using try-catch-throw to provide a user an understandable message for a system generated exception.

But a WCF service is consumed by some other application, not an end user. If something goes wrong in a service, the developer of the client application should know what's going wrong in the service. Again, the client application developer shouldn't know each and every exception in detail, it may lead to some security issues. Also, sometimes a client should be instructed using exceptions.

Again, the Exception class is .NET specific and a WCF Service is consumed by an application that may be in some other language like Java, PHP, ROR and so on. So exceptions may or may not be understood by the client applications.

So, things should be under the control of the service end. For this we have FaultException and FaultContract. Now, let's dive into exception handling in WCF.

Since the service and client applications are interacting with each other using SOAP, we need to exception details in SOAP format. We can use FaultException &/or FaultContract (in System.ServiceModel namespace) to these exception details to the client.

FaultException

Let's see how to use a FaultException. 

You need to create an instance of the FaultException class with FaultReason/FaultCode/MessageFault and throw it.

In the client application add a catch block with an instance of FaultException and use it's properties.

FaultContract

If you want to send some additional details (maybe to describe some business requirements) to the client then you can use a FaultContract.

Create a custom class with properties for holding the details you want to send to the client application.

Decorate this custom class with a DataContract attribute and it's properties with a DataMember attribute.

Decorate the method with a FaultContract attribute with the type of object you want to throw.

In the client application, create a catch block with an instance of the custom fault class and use it's properties.
-----------------------------------------------------------------------------------------------------------------------------

Q)Service Behavior In WCF
The [Service Behavior] attribute is used to apply behavior at the service level. It allows you to control things such as: 

  • Concurrency
  • Throttling
  • Transaction
  • Session Management
  • Thread Behavior

The preceding can be done by setting its properties. 

·        Address Filter Mode

·         Automatic Session ShutDown

·         Concurrency Mode

·         IgnoreExtensionDataObject

·         IncludeExceptionDetailinFaults

·         InstanceContextMode

·         MaxItemsinObjectGraph

·         ReleaseServiceInstanceOnTransactionComplete

·         TransactionAutoCompleteOnSessionClose

·         TransactionTimeOut

Session management and the Concurrency are really important and are the most useful properties in Service Behavior.

 

Explain transactions in WCF?

A transaction is a logical unit of work consisting of multiple activities that must either succeed or fail together. For example, you are trying to make an online purchase for a dress; your amount is debited from the bank, but your ordered dress was not delivered to you. So what did you get from the preceding example? Bank operations hosted in a separate service and the online purchase service (Ordering the goods) hosted as another separate service. For the preceding example the online purchase service did not work well as expected due to the database query error, without knowing it the Bank operations were completed perfectly. For this we really need transactions to ensure that either of the operations should succeed or fail. Before we go to the WCF transactions, let us discuss what exactly are the basics behind the transactions.

The following are the types of the Transactions:

  1. Atomic
  2. Long Running

Atomic transactions are the ones that take less time to finish, for example updating the relative tables in the database. As I said in the last paragraph, the bank related operation table got updated, but the Purchase related tables were not updated. This we can call as an Atomic Transaction.

Long Running transactions are the ones that take more time to finish. For example, a client sending a request to the service but it takes more days or months to provide a response to the client. Yes of course until that period of time has completed we should not lock down the resources like SQL Server, so this case cannot be handled by Atomic Transactions.

Transaction Protocols 

  • Lightweight Protocol
  • OleTx Protocol
  • WSAT Protocol

Lightweight Protocol: It is used when a single application inside an appdomain is working with a single RM (SQL Server or any component participating in transactions).

OleTx Protocol: It allows Cross AppDomain, used for Windows-intranet scenarios. No cross-platform communication allowed, no communication through the firewall is allowed.

WSAT Protocol: Similar to OleTx, but this will go across firewalls and platforms.

I hope the preceding one is still unclear for you guys, let me try to explain it in another way. A WCF service calls into SQL Server for multiple updates to be done, that are all enlisted as a single transaction. A WCF service is called by the clients running on the same machine or various Windows machine. In this case OleTx protocol is used to maintain the transaction. In the same above situation if one of your clients is a Java client, the WSAT protocol will be used since it is a cross-platform interoperability.

 

WCF Transactions

Now to see here how the transactions will be done using WCF. The following is the really important procedure to configure transactions.

  • Transaction Bindings
  • Transaction Flow Option
  • TransactionScope (Client and Server)
  • Configuring Transaction Modes

Transaction Bindings

Before you think about achieving the transaction in WCF, we need to consider the binding to choose, not all bindings normally support transactions. The following are the bindings that support transactions:

  • NetNamedPipeBinding
  • NetTCPBinding
  • WSHttpBinding
  • WSDualHttpBinding
  • WSFederationHttpBinding

NetNamedPipeBinding and NetTCPBinding support transactions because they deal with AppDomains very well, either in the same machine or another machine.

WS bindings are not an issue, they implement the Web Services Enhancement standards (WSE) namely WS-Atomic Transaction. The following is the declaration of the binding:

<bindings> 

<wsHttpBinding> 

<binding name="wshttpbind" transactionFlow="true"></binding> 

</wsHttpBinding> 

</bindings> 

Transaction Flow Option

We should declare this option in the service interface methods. The following are the three sets of options available:

  • Transaction Flow option: Not Allowed
  • Transaction Flow option: Allowed
  • Transaction Flow option: Mandatory

Transaction Flow Option: Not Allowed

The client cannot propagate its transaction into the service operation, even if the binding supports transactions. Even if the client propagates its transaction, it will be simply ignored, no exception will be thrown. 

Transaction Flow Option: Allowed

The service operation allows the transaction propagation if the client wants to. That is, the client creates the transaction, the binding that you are using also supports transactions. If the transaction flow option is allowed in the service method then the transaction will be propagated to the service. In other words the transaction will not be Propagated. What if, when the client propagates the transaction, the binding in the service does not support transactions? As a result an exception will be thrown when the client propagates the transaction.

Transaction Flow Option: Mandatory

The client and the service must use the binding that supports transactions, any violations will result in an exception. 

Transaction Scope

We will now discuss two important attributes we need to define in the transaction, they are TransactionScopeRequired and the TransactionAutoComplete properties in operation behavior.

TransactionScopeRequired: True, it means if the client propagates the transaction to the operation, it will be the one to use in the service side. If the client did not propagate any transaction then it creates its own transaction and uses it. Please look at the following source code to understand how we should declare it in the client and server side.

 TransactionAutoComplete: True, this setting instructs the WCF to auto-commit the transaction at the end of the code block. It can be configured only at the service level.

Configuring Transaction Modes

So far we have learned about the usage of transaction attributes, now let's see various options in configuring transaction modes.

Use Client's T or Use your OWN T

Did you understood the Title "Use Client's T or Use your OWN T"? I hope you couldn't .

Yes, let me explain it here. The following procedure will determine whether the client's transaction is propagated or otherwise create your own transaction and use it.

  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of the operation contract to True

If you are still not clear then please refer to the attached source code.

Use only Client's T

Yes the following procedure determines whether the Hello Service, doesn't use or create a transaction, use only the client's transaction. 

  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Mandatory on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True

Use only Service's T

The following procedure determines whether that Hello Service, doesn't use another transaction, use your own transaction (Service)

  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Not Allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True

Don't use T

The following procedure determines whether that Hello Service, doesn't use any transaction.

  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Not Allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True

So far we have seen what transactions are. What are all the types of protocols it uses? What are all the procedures involved in configuring transactions in WCF? How should we configure different transaction modes? Now we shall see what exactly the process involved during the transaction. The transactional manager manages the transactions across the process or boundaries. It uses either the OleTx Protocol or the WSAT protocol to manage, namely the Distributed Transaction Manager (DTC). DTC actually uses the management protocol 2 Phase Commit Protocol to manage the distributed transaction across machines. There are two phases that DTM uses to manage the distributed transaction.

  • Prepare
  • Commit

In the Prepare phase, DTC asks each resource manager (SQL) to vote on either commit or abort through an RPC call, then each Resource manager (SQL) gives their votes to DTC saying Yes or No.

In the Commit phase, DTC asks all resource managers to commit or abort based on the votes received yes or no.

Coordinator Cohort
QUERY TO COMMIT
-------------------------------->
VOTE YES/NO prepare*/abort*
<-------------------------------
commit*/abort* COMMIT/ROLLBACK
-------------------------------->
ACKNOWLEDGMENT commit*/abort*
<--------------------------------
end

 

But please don't worry about which transaction manager I need to use, how I need to manage and all, because all these operations are managed by the WCF internally. Please refer to the attached code for further details.

 

Throttling

Service Behavior: Throttling exposes properties that you can control how many instances or sessions are created at the application level. For example the number of service instances, the creating should not be more than the specific value.

 

MaxConcurrentCalls

To define the number of concurrent calls that the service will accept. The default value in .Net 4.0 is 16 * processor count. Prior to .Net 4.0 it was 16.

 

MaxConcurrentSessions

To define the number of session channels that the service will accept. By default in .Net 4.0 the default value is 100 * processor count, prior to .Net 4.0 the default value was 10.

 

MaxConcurrentInstances

To define the number of service instances will be created. By default in .Net 4.0 the default value will be 26, whereas in .Net 4.0 the default value will be 116 * processor count.
-----------------------------
------------------------------------------------------------------------------------------------

Explain what is DataContractSerializer?

WCF provides a message-oriented programming framework. We use WCF to transmit messages between applications. Internally WCF represents all the messages by a Message class. When WCF transmits a message it takes a logical message object and encodes it into a sequence of bytes. After that WCF reads those bytes and decodes them in a logical object. The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF receives the logical message, it transforms them back into corresponding .Net objects. This process is called serialization.

WCF supports three basic serializers:

XMLSerializer

NetDataContractSerializer

DataContractSerializer

WCF deserializes WCF messages into .Net objects and serializes .Net objects into WCF messages. WCF provides DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like XMLSerializer.

The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all operation contracts. You can also set a separate contract for each operation.

XMLSerializer

We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this serialization from .Net 1.0. It is used by default with the ASP.Net webservices (ASMX).

NetDataContractSerializer

NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible with [Serializable] types. It is not recommended for service oriented design.

DataContractSerializer

DataContractSerializer is a default serializer for WCF. We need not to mention DataContractSerializer attribute above the service contract.
-----------------------------------------------------------------------------------------------------------------------------

 Q)What is WCF Concurrency and How many modes are of Concurrency in WCF?

WCF Concurrency means “Several computations are executing simultaneously.

WCF concurrency helps us configure how WCF service instances can serve multiple requests at the same time. You will need WCF concurrency for the below prime reasons; there can be other reasons as well but these stand out as important reasons:

We can use the concurrency feature in the following three ways

Single

Multiple

Reentrant

Single: A single request will be processed by a single thread on a server at any point of time. The client proxy sends the request to the server, it process the request and takes another request.

The following is the declaration of Concurrency.Single:

Concurrency

Multiple: Multiple requests will be processed by multiple threads on the server at any point of time. The client proxy sends multiple requests to the server. Requests are processed by the server by spawning multiple threads on the server object.

Reentrant: The reentrant concurrency mode is nearly like the single concurrency mode. It is a single-threaded service instance that receives requests from the client proxy and it unlocks the thread only after the reentrant service object calls the other service or can also call a WCF client through call back.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Tracing in WCF?

Answer: The tracing mechanism in the Windows Communication Foundation is based on the classes that reside in the System.Diagnostic namespace. The important classes are Trace, TraceSource and TraceListener.

Configuring WCF to emit tracing information/Define Trace Source, we have the following options:

System.ServiceModel

System.ServiceModel.MessageLogging

System.ServiceModel.IdentityModel

System.ServiceModel.Activation

System.Runtime.Serialization

System.IO.Log

Cardspace
-----------------------------------------------------------------------------------------------------------------------------

Q) Why ASP.NET Web API (Web API)?

Today, a web-based application is not enough to reach it's customers. People are very smart, they are

using iphone, mobile, tablets etc. devices in its daily life. These devices also have a lot of apps for

making the life easy. Actually, we are moving from the web towards apps world.

So, if you like to expose your service data to the browsers and as well as all these modern devices

apps in fast and simple way, you should have an API which is compatible with browsers and all these

devices.

For example twitter,Facebook and Google API for the web application and phone apps.

Web API is the great framework for exposing your data and service to different-different devices.

Moreover Web API is open source an ideal platform for building REST-ful services over the .NET

Framework. Unlike WCF Rest service, it use the full features of HTTP (like URIs, request/response

headers, caching, versioning, various content formats) and you don't need to define any extra config

settings for different devices unlike WCF Rest service.

Web API Features:

Supports convention-based CRUD actions, since it works with HTTP verbs GET,POST,PUT and DELETE.

Responses have an Accept header and HTTP status code.

Supports multiple text formats like XML, JSON etc. or you can use your custom MediaTypeFormatter.

May accepts and generates the content which may not be object oriented like images, PDF files etc.

Automatic support for O Data. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for O Data query composition.

Supports Self-hosting or IIS Hosting.

Supports the ASP.NET MVC features such as routing, controllers, action results, filter, model binders,

IOC container or dependency injection.
-----------------------------------------------------------------------------------------------------------------------------

Q) Why choose Web API?

If you need a Web Service and don’t need SOAP, then ASP.NET Web API is the best choice.

Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.

Easy configuration, unlike WCF REST service.

Simple service creation with Web API. With WCF REST Services, service creation is difficult.

Based on HTTP and so easy to define, expose and consume in a REST-ful way.

Based on lightweight Restful architecture and good for devices that have limited bandwidth like smartphones.

Open Source.
-----------------------------------------------------------------------------------------------------------------------------

Q) Difference between ASP.NET MVC and ASP.NET Web API?

Asp.Net Web API VS Asp.Net MVC:

Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view.

Web API helps to build REST-ful services over the .NET Framework and it also supports content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON, XML, ATOM or other formatted data), self-hosting which are not in MVC.

Web API also takes care of returning data in particular format like JSON, XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.

In Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.

Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing, and other MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these features exist within.System.Web.Mvc Hence Web API can also be used with Asp.Net and as a stand-alone service layer.

You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML, or any other format, and building a full-blown HTTP service. Typically, this will be called Web API self-hosting.

When you have mixed MVC and Web API controllers and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since both are different.

Moreover, Web API is lightweight architecture and except for the web application, it can also be used with smartphone apps.
-----------------------------------------------------------------------------------------------------------------------------

Q) Difference between WCF and Web API and WCF REST and Web Service?

Web Service:

It is based on SOAP and returns data in XML form.

It supports only HTTP protocol.

It is not open source but can be consumed by any client that understands XML.

It can be hosted only on IIS.

WCF:

It is also based on SOAP and return data in XML form.

It is the evolution of the web service (.ASMX) and supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ.

The main issue with WCF is its tedious and extensive configuration.

It is not open source but can be consumed by any client that understands XML.

It can be hosted within the application or on IIS or using Windows service.

WCF Rest:

To use WCF as a WCF Rest service you have to enable webHttpBindings.

It supports HTTP GET and POST verbs by [WebGet] and [Web Invoke] attributes respectively.

To enable other HTTP verbs you have to do some configuration in IIS to accept the request of that particular verb on .svc files

Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

It supports XML, JSON, and ATOM data format.

Web API:

This is the new framework for building HTTP services in an easy and simple way.

Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

Unlike the WCF Rest service, it uses the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

It can be hosted within the application or on IIS.

It is lightweight architecture and good for devices that have limited bandwidth like smartphones.

Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML, or whatever format you want to add as a MediaTypeFormatter.

To Whom Choose Between WCF or WEB API:

Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication, etc.

Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

Choose Web API when you want to create a resource-oriented service over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iPhone, and tablets.
-----------------------------------------------------------------------------------------------------------------------------

Q) Comparing Asp.Net Web API Routing and Asp.Net MVC Routing

As you know, Routing is a pattern matching system that monitors the incoming request and figure out what to do with that request. A URL pattern is matched against the routes patterns defined in the Route dictionary in an Order and the first match wins. This means the first route which successfully matches a controller, action, and action parameters defined in the URL will call into the specified controller and action.

Asp.Net MVC application and Asp.Net Web API must have at least one route defined in order to function. Hence, Visual Studio templates defined for MVC and Web API must have a default route. Now let's understand the difference between Asp.Net MVC and Asp.Net Web API.

Default Route Pattern:

The default route pattern for a Web API Project is defined as follows-

config.Routes.MapHttpRoute(

 name: "DefaultApi", //route name

 routeTemplate: "api/{controller}/{id}", //route pattern

 defaults: new { id = RouteParameter.Optional } //parameter default values

 );

The literal api at the beginning of the Web API route pattern, makes it distinct from the standard MVC route. This is not mandatory but it is a good convention to differ Web API route from MVC route.

In Web API route pattern {action} parameter is optional but you can include an {action} parameter. Also, the action methods defined on the controller must be having an HTTP action verb as a prefix to the method name in order to work. So, you can also define the route for Web API as follows-

config.Routes.MapHttpRoute(

 name: "DefaultApi",//route name

 routeTemplate: "api/{controller}/{action}/{id}",//route pattern

 defaults: new { id = RouteParameter.Optional }//parameter default values

 );

routes.MapRoute(

 name: "Default", //route name

 url: "{controller}/{action}/{id}", //route pattern

 defaults: new

 {

 controller = "Home",

 action = "Index",

 id = UrlParameter.Optional

 } //parameter default values

 );

As you have seen there is no literal before at the beginning of the Asp.Net MVC route pattern but you can add if you wish.

Route Processing

In Web API route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT, DELETE) or have one of the HTTP action verbs as a prefix for the Actions methods name as given below-

public class ValuesController : ApiController

{

 // GET api/

 public IEnumerable Get()

 {

 return new string[] { "value1", "value2" };

 }

 // GET api//5

 public string Get(int id)

 {

 return "value";

 }

 // POST api/

 public void Post([FromBody]string value)

 {

 }

 // PUT api//5

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

 {

 }

 // DELETE api//5

 public void Delete(int id)

 {

 }

}

// OR You can also defined above API Controller as Verb Prefix

public class ValuesController : ApiController

{

 // GET api/values

 public IEnumerable GetValues()

 {

 return new string[] { "value1", "value2" };

 }

 // GET api/values/5

 public string GetValues(int id)

 {

 return "value";

 }

 // POST api/values

 public void PostValues([FromBody]string value)

 {

 }

 // PUT api/values/5

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

 {

 }

 // DELETE api/values/5

 public void DeleteValues(int id)

 {

 }

}

In Asp.Net MVC route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request are selected. The Action methods defined in the MVC controller do not have HTTP action verbs as a prefix for the Actions methods but they have names like as normal method as shown below-

public class HomeController: Controller

{

 // GET: /Home/Index

 public ActionResult Index() //method - Index

 {

 // To Do:

 return View();

 }

 // Post: /Home/Index

 [HttpPost]

 public ActionResult Index(LoginModel model, string id)

 {

 // To Do:

 return View();

 }

}

In MVC, by default HTTP verb is GET for using other HTTP verbs you need to be defined it as an attribute but in Web API you need to define it as a method's name prefix.

Complex Parameter Processing:

Unlike MVC, URLs in Web API cannot contain complex types. Complex types must be placed in the HTTP message body and there should be only one complex type in the body of an HTTP message.

Base Library:

Web API controllers inherit from, but MVC controllers inherit from System.Web.MVC.Controller. Both the libraries are different but act in a similar fashion.
-----------------------------------------------------------------------------------------------------------------------------

Q)Security in WebAPI

Authentication

Authentication is all about the identity of the end-user. It's about validating the identity of a user who is accessing our system, that he is authenticated enough to use our resources or not. Does that end-user have valid credentials to log into our system? Credentials can be in the form of a user name and word. We'll use the Basic Authentication technique to understand how to do authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to do security. Authorization means what all the permissions are that the authenticated user must have to access web resources. Are they allowed to access/perform an action on that resource? This could be done by setting roles and permissions for an end-user who is authenticated or can be done by providing a secure token, using which an end-user can have access to other services or resources.

Maintaining Session

RESTful services work on a stateless protocol, in other words HTTP. We can maintain sessions in the Web API using token-based authorization techniques. An authenticated user will be allowed to access resources for a specific period of time and can re-instantiate the request with an increased session time delta to access other resource or the same resource. Websites using WebAPIs as RESTful services may need to implement login/logout for a user, to maintain sessions for the user, to provide roles and permissions to their user, all these features could be done using basic authentication and token-based authorization. I'll explain this step-by-step.
-----------------------------------------------------------------------------------------------------------------------------

Q) Securing ASP.NET Web API using basic Authentication

Basic HTTP Authentication

In basic HTTP authentication, the client passes their username and password in the HTTP request header. Typically, using this technique we encrypt user credentials string into base64 encoded string and decrypt this base64 encoded string into plain text. You can also use another encryption and decryption technique.

Custom Principal:

Since WebAPI is built on the top of ASP.NET Framework, hence it can use ASP.NET Framework features like ASP.NET membership and provider. ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. For ASP.NET Web API, you can also create a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well as the current thread.

public class CustomPrincipal : IPrincipal

 {

 public IIdentity Identity { get; private set; }

 public bool IsInRole(string role)

 {

 if (roles.Any(r => role.Contains(r)))

 {

 return true;

 }

 else

 {

 return false;

 }

 }

 public CustomPrincipal(string Username)

 {

 this.Identity = new GenericIdentity(Username);

 }

 public int UserId { get; set; }

 public string FirstName { get; set; }

 public string LastName { get; set; }

 public string[] roles { get; set; }

 }

Now you can put these CustomPrincipal objects into the thread’s current principle property and into the HttpContext’s User property to accomplish your custom authentication and authorization process.

Custom ASP.NET Web API Authorization Filter

Like ASP.NET MVC, Web API also provides an Authorization filter to authorize a user. This filter can be applied to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class that exist in System.Web.Http namespace. You can customize this filter by overriding OnAuthorization() method as shown below:

//custom authorize filter attribute

public class CustomAuthorizeAttribute : AuthorizeAttribute

{

 private const string BasicAuthResponseHeader = "WWW-Authenticate";

 private const string BasicAuthResponseHeaderValue = "Basic";

 readonly DataContext Context = new DataContext();

 public string UsersConfigKey { get; set; }

 public string RolesConfigKey { get; set; }

 protected CustomPrincipal CurrentUser

 {

 get { return Thread.CurrentPrincipal as CustomPrincipal; }

 set { Thread.CurrentPrincipal = value as CustomPrincipal; }

 }

 public override void OnAuthorization(HttpActionContext actionContext)

 {

 try

 {

 AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;

 if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter) && authValue.Scheme == BasicAuthResponseHeaderValue)

 {

 Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);

 if (parsedCredentials != null)

 {

 var user = Context.Users.Where(u => u.Username == parsedCredentials.Username && u.Password == parsedCredentials.Password).FirstOrDefault();

 if (user != null)

 {

 var roles = user.Roles.Select(m => m.RoleName).ToArray();

 var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];

 var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];

 Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;

 Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

 CurrentUser = new CustomPrincipal(parsedCredentials.Username, roles);

 if (!String.IsNullOrEmpty(Roles))

 {

 if (!CurrentUser.IsInRole(Roles))

 {

 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);

 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);

 return;

 }

 }

 

 if (!String.IsNullOrEmpty(Users))

 {

 if (!Users.Contains(CurrentUser.UserId.ToString()))

 {

 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);

 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);

 return;

 }

 }

 }

 }

 }

 }

 catch (Exception)

 {

 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);

 return;

 

 }

 }

 private Credentials ParseAuthorizationHeader(string authHeader)

 {

 string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });

 if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))

 return null;

 return new Credentials() { Username = credentials[0], Password = credentials[1], };

 }

}

//Client credential

public class Credentials

{

 public string Username { get; set; }

 public string Password { get; set; }

}

Applying CustomAuthorize attribute

To make secure your service, decorate your Web API controllers with CustomAuthorize attribute as defined above and specify the uses or roles to access specific service actions/methods. The below product service action Getproduct can be access only by Admin users.

public class ProductController : ApiController

{

 [CustomAuthorize(Roles="Admin")]

 public HttpResponseMessage Getproducts()

 {

 var products = new Product[]

 {

 new Product()

 {

 Id = 1,

 Name = "Soap",

 Price =25.12

 },

 new Product()

 {

 Id = 2,

 Name = "Shampoo",

 Price =25.12

 }

 };

 var response = Request.CreateResponse>(HttpStatusCode.OK, products);

 return response;

 }

}

Calling Web API and passing client credential from ASP.NET MVC

public class HomeController : Controller

{

 //

 // GET: /Home/

 public ActionResult Index()

 {

 string FullName = User.FirstName + " " + User.LastName;

 HttpClient client = new HttpClient();

 string authInfo = "admin" + ":" + "123456";

 authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

 client.BaseAddress = new Uri("http://localhost:63173/");

 HttpResponseMessage response = client.GetAsync("api/product/").Result;

 if (response.IsSuccessStatusCode)

 {

 // Parse the response body. Blocking!

 var data = response.Content.ReadAsAsync>().Result;

 return View();

 }

 return View();

 }

}
-----------------------------------------------------------------------------------------------------------------------------

Q) Token Based Authentication in ASP.NET Web API

ASP.NET Web API is a service which can be accessed over the HTTP by any client. So, providing security to the Web API is very important, which can be easily done with the process called Token based authentication. Token-based authentication is a process where the user sends his credential to the server, server will validate the user details and generate a token which is sent as response to the users, and user store the token in client side, so client do further HTTP call using this token which can be added to the header and server validates the token and send a response. This article will give you a step by step process to implement the token-based authentication in ASP.NET Web API 2.

Implementation of Token Based Authentication

Step 1

Open visual studio 2017 => create a new Web API project => Name the project, in my case, I named it as Token_Auth_Web_API, set the Authentication to Individual User Account as shown in below figure.



Step 2

Go to Startup.cs file under App_Start folder in the solution

// Configure the application for OAuth based flow

 PublicClientId = "self";

 OAuthOptions = new OAuthAuthorizationServerOptions

 {

 TokenEndpointPath = new PathString("/Token"),

 Provider = new ApplicationOAuthProvider(PublicClientId),

 AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),

 AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),

 // In production mode set AllowInsecureHttp = false

 AllowInsecureHttp = true

 };

Install the Owin using the below command in package manager console

Install-Package Owin -Version 1.0.0

Owin: open web interface for .NET is a middleware which defines the interface between the web server and application.

TokenEndPointPath: This is a kind of request path client applications which communicate with the server directly as part of the OAuth protocol. It must begin with slash “/”

Provider: The object provided by the application to process the event raised by the authorization server middleware.

AuthorizeEndpointPath: The request path where the client application will redirect the client/user to obtain user account to issue a token

AccessTokenExpireTimeSpan : Defines the validity of token

AllowInsecureHttp: It will allow a normal http request to authorize, if it is set to false, it will process only https request.

Step 3

To register the user, we are going to using api/Account/Register Endpoint from a client which is available in AccountController of our WEB API project, as shown below.

// POST api/Account/Register

 [AllowAnonymous]

 public async Task<IHttpActionResult> Register(RegisterBindingModel model)

 {

 if (!ModelState.IsValid)

 {

 return BadRequest(ModelState);

 }

 var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

 IdentityResult result = await UserManager.CreateAsync(user, model.Password);

 

 if (!result.Succeeded)

 {

 return GetErrorResult(result);

 }

 

 return Ok();

 }

Go to the Index View of the home controller, as shown in below figure and add the below code

Home=> Index.cshtml

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

 <h4> Registration Form</h4>

 <div id="loginDiv" style="width:50%">

 <div style="width:50%">

 <div class="form-group">

 <label for="txtEmail">First Name </label>

 <input type='email' name="email" id="txtEmail" class="form-control">

 </div>

 <div class="form-group">

 <label>Password</label>

 <input type="password" id="textPwd" class="form-control">

 </div>

 <div class="form-group">

 <label>Confrim Password</label>

 <input type="password" id="txtConfirmPwd" class="form-control">

 </div>

 </div>

 <button id="register" class="btn btn-default">Submit</button>

 </div>

 <h4>Login </h4>

 

 <div id="loginDiv" style="width:50%">

 <div class="form-group">

 <label for="txtEmail">First Name </label>

 <input type='email' name="email" id="loginEmail" class="form-control">

 </div>

 <div class="form-group">

 <label>Password</label>

 <input type="password" id="loginPwd" class="form-control">

 </div>

 <button id="btnLogin" class="btn btn-default">Submit</button>

 </div>

 <div>

 <label id="msg"></label>

 </div>

 <script>

 $(document).ready(function () {

 $("#register").on('click', function () {

 var data = { Email: $("#txtEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#txtConfirmPwd").val().trim() };

 $.ajax({

 url: "http://localhost:49501/api/Account/Register",

 type: 'POST',

 data: data,

 success: function (resp) {

 window.location.href = '/Home/Index';

 }

 })

 });

 

 $("#btnLogin").on('click', function () {

 //var data = { Email: $("#loginEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#loginPwd").val().trim() };

 $.ajax(

 {

 url: "/TOKEN",

 type: "POST",

 data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }),

 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

 success: function (resp) {

 sessionStorage.setItem('userName', resp.userName);

 sessionStorage.setItem('accessToken', resp.access_token);

 var authHeaders = {};

 authHeaders.Authorization = 'Bearer ' + resp.access_token;

 $.ajax({

 url: "http://localhost:49501/api/values",

 type: "GET",

 headers: authHeaders,

 success: function (response) {

 $("#loginEmail").val("");

 $("#loginPwd").val("");

 $("#msg").text(response);

 }

 });

 },

 error: function () {

 $("#msg").text("Authentication failed");

 }

 })

 });

 

 })

 </script>

 

From the above HTML code, it is obvious we have two form

Registration Form

Login Form

 


 

Registration Form: Registration Form is used to register the user using the /api/Account/Register API Service which doesn’t require any authentication

Login Form: In this user request to give their credential, once they submit the form /TOKEN post service is fired, once the service validates the user it will generate an access token and send it is as a response to a server with username as shown in below figure.

In Login Ajax call success, we are saving the token and user details, and making another API call /api/values, this function definition is decorated with [Authorize] attribute. we need to pass the access token as an authorization header whenever this HTTP service request happens from the client side.

 // GET api/values

 [EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-My-Header")]

 [Authorize]

 public IEnumerable<string> Get()

 {

 return new string[] {"You are successfully Authenticated to Access the Service"};

 }

[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-My-Header")] : Enabled the CROS origin, so that it can be accessed from any domain

[Authorize] : It is used to authenticate the token send from the client side, once the authentication is successfully the Get() will be fired

Client-side HTTP request with Authorization Header

 $("#btnLogin").on('click', function () {

 $.ajax(

 {

 url: "/TOKEN",

 type: "POST",

 data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }),

 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

 success: function (resp) {

 sessionStorage.setItem('userName', resp.userName);

 sessionStorage.setItem('accessToken', resp.access_token);

 var authHeaders = {};

 authHeaders.Authorization = 'Bearer ' + resp.access_token;

 $.ajax({

 url: "http://localhost:49501/api/values",

 type: "GET",

 headers: authHeaders,

 success: function (response) {

 $("#loginEmail").val("");

 $("#loginPwd").val("");

 $("#msg").text(response);

 }

 });

 

 },

 error: function () {

 $("#msg").text("Authentication failed");

 }

 })

authHeaders.Authorization = 'Bearer ' + resp.access_token : We are defining the authorization header with the access token when the /api/values HTTP call happens. In server side, the token is validated, once its success it will return a message “You are successfully Authenticated to Access the Service”

Note: we need to send grant_type: 'password' as the data along with user name and password through the body of HTTP request which accessing the URL /TOKEN

 


Header with /api/values HTTP Call

 


 



If the credential is wrong the service /TOKEN will return the error message which is shown above
----------------------------------------------------------------------------------------------------------------------------

Q)Dependency injection in asp.net web api
Dependency Injection aka DI is a way in which one object (The Doctor) is capable to give the dependencies of another object (The patient) as per the need.

Dependency Injection Containers

In the above scenario, different doctors have different ways of treating the illness or giving you the service as per need. Similarly, there are different kinds, popularly known as containers, of dependency injection. In other ways, different design patterns for the dependency injection containers. Below are few of them.

Castle Windsor : This is one of the mature and best Inversion of Control container for .NET and Silverlight applications

Unity : If you are looking for Lightweight extensible dependency injection container, Unity is one of the container you can select from. It comes with support for constructor, property, and method call injection

Autofac : One of the preferred IoC

DryIoc : Simple, fast and fully featured IoC container.

Ninject : Called as ninja of .NET dependency injectors

StructureMap : The original IoC/DI Container for .Net

Spring.Net

Open source application framework

LightInject : An ultra-lightweight IoC container

Simple Injector : An easy-to-use Dependency Injection (DI) library for .NET 4+, It can support Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.

Microsoft.Extensions.Dependency Injection : A default IoC container in-built in ASP.NET Core applications.

Scrutor : An extensions for Microsoft.Extensions.Dependency Injection which supports assembly scanning

VS MEF : Managed Extensibility Framework (MEF) implementation used by Visual Studio.

TinyIoC : Best for small scale projects as it’s easy to use and hassle free as well.

Let us understand the ninja of .Net dependency injection, The Ninject.

Introduction to Ninject in ASP.NET Web API

Ninject is a light-weighted, flexible and open source dependency injector for .Net applications. Due to its flexible nature, managing the application at code level becomes easier and reusable. Ninject is hosted in GitHub. For more details about its advantages and the differences between older-newer versions, you can visit https://github.com/ninject/Ninject

Configuring the Ninject in Web API2

Let’s now see how we can introduce Ninject in our application. I will consider the same example, I created in the article Content Negotiation in ASP.NET WebAPI, I will be enabling the ProductController to use the Ninject Dependecy Injection to exchange the desired data and for testing will be using POSTMAN. If you are unaware of POSTMAN, I would suggest you to first go through Understanding Model Binding in ASP.NET Web API. Here I have explained and how to use POSTMAN. So now let’s get started with the Ninja, The NINJECT!! Current the ProductsController looks as below :



STEP 1

Create an Interface with in the model folder as follows

 public interface IProducts

 {

 IQueryable<Product> LoadProducts();

 }

Please Note, for time being I am only converting the first action method ‘LoadProducts’ to use Ninject. This method brings all the product data from server.

STEP 2

For the body of the method in the interface, I will make database call. To achieve that, first I created a Service Folder under the root project. In that folder, I created a service class ‘ProductService’ which inherits the interface ‘IProducts’. The class looks as follows

 public class ProductService : IProducts

 {

 private AdventureWorksEntities db = new AdventureWorksEntities();

 public IQueryable<Product> LoadProducts()

 {

 return db.Products;

 }

 } 

STEP 3

Now let us change our ProductsController code to use the interface and the service class.

 private readonly IProducts productRepository;

 public ProductsController(IProducts product_Repository)

 {

 this.productRepository = product_Repository;

 }

 [HttpGet]

 // GET: api/Products

 public IQueryable<Product> LoadProducts()

 {

 //return db.Products;

 return productRepository.LoadProducts();

 }

STEP 4

Now finally the time comes, the time to include The Ninja of Dependency Injection, Ninject in the application. To incorporate Ninject with in the application, firstly we need to install two packages.

Ninject.Web.WebApi

Ninject.Web.WebApi.WebHost

Both the packages are available in Nuget. You can install it either of the way mentioned below,

Right click on project => select Manage NuGet packages =>Browse and install the required packages

Tools => NuGet Package Manager => Package Manager Console

2.1. If you have multiple projects, you need to select the correct project where you want to install the package.

2.2. PM => Install-Package Ninject.Web.WebApi

PM => Install-Package Ninject.Web.WebApi.WebHost

Note that when we install Ninject.Web.WebApi, two more packages get installed automatically

Ninject

Ninject.Web.Common

Whereas when you install Ninject.Web.Common.WebHost, it installs WebActivatorEx package and also add a new class called Ninject.Web.Common.cs with in App_Start directory.

STEP 5

Now the last step. To enable the use of ProductService class via IProduct interface, we first need to bind them. For this, go to the ‘RegisterServices’ method in ‘Ninject.Web.Common.cs’ file with in App_Start directory.

 private static void RegisterServices(IKernel kernel)

 {

 kernel.Bind<IProducts>().To<ProductService>();

 }

Here we are done with making changes in the code to configure Ninject Dependency Injector container. Let’s go ahead and test it using Postman.



 Similarly you can change the code structure for other action methods to use Ninject.

Summery

Dependency Injection being one of the way in which re-usability and maintaining the application at code level becomes easy, Ninject serves as a strong open-source IoC for .Net application. Its easily available via Nu Get Manager and also under implementing the same is easier.

-----------------------------------------------------------------------------------------------------------------------------

Q) What are the new features introduced in ASP.NET Web API 2.0?

The following features have been introduced in ASP.NET Web API 2.0:

Attribute Routing

CORS (Cross-Origin Resource Sharing)

OWIN (Open Web Interface for .NET) self-hosting

IHttpActionResult

Web API OData etc.
-----------------------------------------------------------------------------------------------------------------------------

Q)Can we return View from Web API?

No, Web API does not return View but they return the data. APIController is meant for returning the data. So, if you need to return a view from the controller class, then make sure to use or inherit the Controller class.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is 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:

HTTP Get: Used to get or retrieve the resource or information only.

HTTP Post: Used to create a new resource on the collection of resources.

HTTP Put: Used to update the existing Response

HTTP Delete: Used to Delete an existing resource.
-----------------------------------------------------------------------------------------------------------------------------

Q)What are HTTP Status Codes?

HTTP Status Code Is 3-digit integer in which the first digit of the Status-Code defines the class of response. Response Header of each API response contains the HTTP Status Code. HTTP Status Codes are grouped into five categories based upon the first number.

S. No.  HTTP Status Code      Description

1.         1XX    Informational

2.         2XX    Success

3.         3XX    Redirection

4.         4XX    Client-Side Error

5.         5XX    Server-Side Error

Table: HTTP Status Code with Description

Some of the commonly seen HTTP Status Codes are: 200 (Request is Ok), 201 (Created), 202 (Accepted), 204 (No Content), 301 (Moved Permanently), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable) etc.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Parameter Binding in ASP.NET Web API?

When Web API calls a method on a controller, it must set the values for the parameters, this particular process is known as Parameter Binding. By Default, Web API uses the below rules in order to bind the parameter:

FromUri: If the parameter is of “Simple” type, then Web API tries to get the value from the URI. Simple Type includes.Net Primitive type like int, double, etc., DateTime, TimeSpan, GUID, string, any type which can be converted from the string type.

FromBody: If the parameter is of “Complex” type, then Web API will try to bind the values from the message body.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Content Negotiation in Web API?

Content Negotiation is the process of selecting the best representation for a given response when there are multiple representations available. Two main headers which are responsible for the Content Negotiation are:

Content-Type

Accept

The content-type header tells the server about the data, the server is going to receive from the client whereas another way to use Accept-Header, which tells the format of data requested by the Client from a server. In the below example, we requested the data from the server in JSON format.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Media-Type Formatter in ASP.NET Web API?

Media-Type formatter is an abstract class from which JsonMediaTypeFormatter (handle JSON format) and XmlMediaTypeFormatter (handle XML format) class derived from. Media-Type formatter are classes responsible for serializing the response data in the format that the client asked for.
-----------------------------------------------------------------------------------------------------------------------------

Q)What is the use of Authorize Attribute?

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

Q)What is Basic HTTP Authentication?

Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client pass username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password”, based encoded.
-----------------------------------------------------------------------------------------------------------------------------

Q)How Web API Routes HTTP request to the Controller ASP.NET MVC?

In ASP.NET Web API, HTTP request maps to the controller. In order to determine which action is to invoke, the Web API framework uses a routing table.
-----------------------------------------------------------------------------------------------------------------------------

Q)In How many ways we can do Web API Versioning?

We can do Web API Versioning in the following ways:

URI

Query String Parameter

Custom Header Parameter

Accept Header Parameter
-----------------------------------------------------------------------------------------------------------------------------

Q)What is Exception handling?

Exception handling is a technique to handle runtime error in the application code. In multiple ways we can handle the error in ASP.NET Web API, some of them are listed below:

HttpResponseException

HttpError

Exception Filters etc.
-----------------------------------------------------------------------------------------------------------------------------

Q)Exception Handling In ASP.NET Web API

Using HttpResponseException

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

Using HttpError

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.

Using Exception Filters

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

We can use exception filter whenever controller action method throws an unhandled exception that is not an HttpResponseException. This is an attribute so we can decorate both action method and controller with this. Exception filter is very similar to HandleErrorAttribute in MVC.

Register Exception Filters

There are many ways to register exception filter but the developers generally follow three approaches to register filter.

Decorate Action with exception filter.

Decorate Controller with exception filter.

Filter Register globally.

To apply the exception filter to the specific action, the action needs to decorate with this filter attribute. In the following example, I have applied CustomExceptionFilter filter to only one part of the action.

To apply the exception filter to all the actions of a controller, the controller needs to be decorated with this filter attribute.

To apply the exception filter to all Web API controllers, the filter needs to register to GlobalConfiguration.Configuration.Filters collection.

Using Exception Handlers

Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.

 

Error inside the exception filter.

Exception related to routing.

Error inside the Message Handlers class.

Error in Controller Constructor.

Web API 2 provides a good alternative way to achieve global exception handling. Web API provides "ExceptionHandler" abstract class to handle exception above said area.

Same as exception filter, Exception handler is also required to be registered. ExceptionHandler is inheriting from IExceptionHandler interface and Web API has already this type of class registered so we just need to replace this class to our custom exception handler class because Web API doesn’t support multiple ExceptionHandler.

Summary

Web API supports many ways of exception handling. Following is a summary of exception handling in Web API described in this article:

We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database.

We can use exception filter to catch unhandled exceptions on action/controllers.

We can use Exception Handlers to catch any type of unhandled exception application-wide.
-----------------------------------------------------------------------------------------------------------------------------


 

 

 

 

 

 




 

 

 

 

 

 



 

Comments

Popular posts from this blog

DOT NET CORE Basic Interview Question and Answers

Angular Basic concepts

Sql server interview questions for experienced