1) What
is Web API?
It is a framework which helps us to build/develop HTTP services.
So there will a client server communication using HTTP protocol.
2) What is
Representational state transfer or REST?
REST is architectural style,
which has defined guidelines for creating services which are scalable.
REST used with HTTP protocol using its verbs GET, POST, PUT and DELETE.
3)
Explain Web API Routing?
Routing is the mechanism of pattern matching as we have in MVC.
These routes will get registered in Route Tables. Below is the sample
route in Web API –
Routes.MapHttpRoute(
Name: "MyFirstWebAPIRoute",
routeTemplate: “api/{controller}/{id}
defaults: new { id = RouteParameter.Optional}
};
defaults: new { id = RouteParameter.Optional}
};
4) List out the differences
between WCF and Web API?
WCF
·
It is framework build
for building or developing service oriented applications.
·
WCF can be consumed by
clients which can understand XML.
·
WCF supports protocols
like – HTTP, TCP, Named Pipes etc.
Web API
·
It is a framework
which helps us to build/develop HTTP services
·
Web API is an open
source platform.
·
It supports most of
the MVC features which keep Web API over WCF.
5) What are the advantages
of using REST in Web API?
REST always used to
make less data transfers between client and server which makes REST an ideal
for using it in mobile apps. Web API supports HTTP protocol thereby it
reintroduces the old way of HTTP verbs for communication.
6) Difference between WCF
Rest and Web API?
WCF Rest
·
“WebHttpBinding” to be enabled for WCF Rest.
·
For each method there
has to be attributes like – “WebGet” and “WebInvoke”
·
For GET and POST verbs
respectively.
Web API
·
Unlike WCF Rest we can
use full features of HTTP in Web API.
·
Web API can be hosted
in IIS or in application.
7) List out differences
between MVC and Web API?
Below are some of the differences between MVC
and Web API
MVC
·
MVC is used to
create a web app, in which we can build web pages.
·
For JSON it will return JSONResult from action
method.
·
All requests are mapped
to the respective action methods.
Web API
·
This is used to create
a service using HTTP verbs.
·
This returns XML or
JSON to client.
·
All requests are
mapped to actions using HTTP verbs.
8) What are the advantages
of Web API?
Below are the lists of
support given by Web API –
·
OData
·
Filters
·
Content Negotiation
·
Self Hosting
·
Routing
·
Model Bindings
9) Can we unit test Web
API?
Yes we can unit test Web API.
10) How to unit test Web
API?
We can unit test the Web API using Fiddler
tool. Below are the settings to be done in Fiddler –
Compose Tab
-> Enter Request Headers -> Enter the Request Body and execute
11) Can we return view
from Web API?
No. We cannot return view from Web API.
12) How we can restrict
access to methods with specific HTTP verbs in Web API?
Attribute programming is used for this functionality. Web API
will support to restrict access of calling methods with specific HTTP verbs. We
can define HTTP verbs as attribute over method as shown below
[HttpPost]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
13) Can we use Web API
with ASP.NET Web Forms?
Yes. We can use Web API with ASP.NET Webforms.
14) List out the steps to
be made for Web API to work in Web Forms?
Below are the steps to
be followed –
·
Creating new
controller for Web API.
·
Adding routing table
to “Application_Start” method in Global.asax
·
Make a AJAX call to
Web API actions.
15) Explain how to give
alias name for action methods in Web API?
Using attribute “ActionName” we can give alias name for Web API actions. Eg:
[HttpPost]
[ActionName("AliasTestAction")]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
[ActionName("AliasTestAction")]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
16) What is the difference between MVC Routing and Web API Routing?
There should be atleast one route defined for MVC and Web API to
run MVC and Web API application respectively. In Web API pattern we can
find “api/” at the beginning which makes it distinct from MVC routing. In Web
API routing “action” parameter is not mandatory but it can be a part of
routing.
17) Explain Exception
Filters?
Exception filters will
be executed whenever controller methods (actions) throw an exception which is
unhandled. Exception filters will implement “IExceptionFilter” interface.
18) Explain about the new
features added in Web API 2.0 version?
Below are the lists of
features introduced in Web API 2.0 –
·
OWIN
·
Attribute Routing
·
External
Authentication
·
Web API OData
19) How can we pass
multiple complex types in Web API?
Below are the methods
to pass the complex types in Web API –
·
Using ArrayList
·
Newtonsoft JArray
20) Write a code snippet
for passing arraylist in Web API?
Below is the code snippet for passing
arraylist –
ArrayList paramList = new ArrayList();
Category c = new
Category { CategoryId = 1, CategoryName = "SmartPhones"};
Product p = new Product { ProductId = 1, Name = "Iphone", Price = 500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p);
Product p = new Product { ProductId = 1, Name = "Iphone", Price = 500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p);
21) Give an example of Web
API Routing?
Below is the sample code snippet to show Web
API Routing –
config.Routes.MapHttpRoute(
name: "MyRoute",//route name
routeTemplate: "api/{controller}/{action}/{id}",//as you can see "api" is at the beginning.
defaults: new { id = RouteParameter.Optional }
);
name: "MyRoute",//route name
routeTemplate: "api/{controller}/{action}/{id}",//as you can see "api" is at the beginning.
defaults: new { id = RouteParameter.Optional }
);
22) Give an example of MVC
Routing?
Below is the sample code snippet to show MVC
Routing –
routes.MapRoute(
name: "MyRoute", //route name
url: "{controller}/{action}/{id}", //route pattern
defaults: new
{
controller = "a4academicsController",
action = "a4academicsAction",
id = UrlParameter.Optional
}
);
name: "MyRoute", //route name
url: "{controller}/{action}/{id}", //route pattern
defaults: new
{
controller = "a4academicsController",
action = "a4academicsAction",
id = UrlParameter.Optional
}
);
23) How we can handle
errors in Web API?
Below are the list of classes which can be
used for error handling -
·
HttpResponseException
·
Exception Filters
·
Registering Exception
Filters
·
HttpError
24) Explain how we can
handle error from “HttpResponseException”?
This returns the HTTP
status code what you specify in the constructor. Eg :
public TestClass MyTestAction(int id)
{
TestClass c = repository.Get(id);
if (c == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return c;
}
{
TestClass c = repository.Get(id);
if (c == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return c;
}
25) How to register Web
API exception filters?
Below are the options to register Web API
exception filters –
·
From Action
·
From Controller
·
Global registration
26) Write a code snippet
to register exception filters from action?
Below is the code snippet for registering
exception filters from action –
[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}
27) Write a code snippet
to register exception filters from controller?
Below is the code snippet for registering
exception filters from controller –
[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}
public class TestCustomerController : Controller
{
//Your code goes here
}
28) Write a code snippet
to register exception filters globally?
Below is the code snippet for registering
exception filters globally –
GlobalConfiguration.Configuration.Filters.Add(
new MyTestCustomerStore.NotImplExceptionFilterAttribute());
29) How to handle error
using HttpError?
HttpError will be used
to throw the error info in response body. “CreateErrorResponse”
method is used along with this, which is an extension method defined in “HttpRequestMessageExtensions”.
30) Write a code snippet
to show how we can return 404 errors from HttpError?
Below is the code
snippet for returning 404 error from HttpError –
string message = string.Format("TestCustomer id = {0} not
found", customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
31) How to enable tracing
in Web API?
To enable tracing place below code in –“Register” method of WebAPIConfig.cs file.
config.EnableSystemDiagnosticsTracing();
32) Explain how Web API
tracing works?
Tracing in Web API done in façade pattern i.e, when tracing for
Web API is enabled, Web API will wrap different parts of request pipeline with
classes, which performs trace calls.
33) Can we unit test Web API?
Yes we can unit test Web API.
34) Explain Authentication in Web API?
Web API authentication
will happen in host. In case of IIS it uses Http Modules for authentication or
we can write custom Http Modules. When host is used for authentication it used
to create principal, which represent security context of the application.
35) Explain ASP.NET Identity?
This is the new
membership system for ASP.NET. This allows to add features of login in our
application.
Below are the lists of
features supported by ASP.NET Identity in Web API –
·
One ASP.NET Identity
System
·
Persistence Control
36) What are
Authentication Filters in Web API?
Authentication Filter
will let you set the authentication scheme for actions or controllers. So this
way our application can support various authentication mechanisms.
37) How to set the
Authentication filters in Web API?
Authentication filters
can be applied at the controller or action level. Decorate attribute –
"IdentityBasicAuthentication” over controller where we have to set the
authentication filter.
38) Explain method –
“AuthenticateAsync” in Web API?
“AuthenticateAsync” method will create “IPrincipal” and will set on
request. Below is the sample code snippet for “AuthenticateAsync” –
Task AuthenticateAsync(
HttpAuthenticationContext mytestcontext,
CancellationToken mytestcancellationToken
)
HttpAuthenticationContext mytestcontext,
CancellationToken mytestcancellationToken
)
39) How to set the Error
Result in Web API?
Below is the sample code to show how to set
error result in Web API –
HttpResponseMessage myresponse = new
HttpResponseMessage(HttpStatusCode.Unauthorized);
myresponse.RequestMessage = Request;
myresponse.ReasonPhrase = ReasonPhrase;
myresponse.RequestMessage = Request;
myresponse.ReasonPhrase = ReasonPhrase;
40) Explain method –
“ChallengeAsync” in Web API?
“ChallengeAsync” method is used to add authentication challenges to response.
Below is the method signature –
Task ChallengeAsync(
HttpAuthenticationChallengeContext mytestcontext,
CancellationToken mytestcancellationToken
)
HttpAuthenticationChallengeContext mytestcontext,
CancellationToken mytestcancellationToken
)
41) What are media types?
It is also called MIME, which is used to identify the data . In
Html, media types is used to describe message format in the body.
42) List out few media
types of HTTP?
Below are the lists of media types –
·
Image/Png
·
Text/HTML
·
Application/Json
43) Explain Media
Formatters in Web API?
Media Formatters in
Web API can be used to read the CLR object from our HTTP body and Media
formatters are also used for writing CLR objects of message body of HTTP.
44) How to serialize
read-only properties?
Read-Only properties can be serialized in Web
API by setting the value “true” to the property –
“SerializeReadOnlyTypes” of class –
“DataContractSerializerSettings”.
45) How to get Microsoft
JSON date format?
Use “DateFormatHandling” property in serializer settings as below –
var myjson =
GlobalConfiguration.Configuration.Formatters.JsonFormatter;
myjson.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
myjson.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
46) How to indent the JSON in web API?
Below is the code snippet to
make JSON indenting –
var mytestjson =
GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
47) How to JSON
serialize anonymous and weakly types objects?
Using “Newtonsoft.Json.Linq.JObject”
we can serialize and deserialize weakly typed objects.
48) What is the use of
“IgnoreDataMember” in Web API?
By default if the
properties are public then those can be serialized and deserialized, if we does
not want to serialize the property then decorate the property with this
attribute.
49) How to write indented
XML in Web API?
To write the indented xml set “Indent” property to true.
50) How to set Per-Type
xml serializer?
We can use method – “SetSerializer”. Below is the sample code snippet for using it –
var mytestxml =
GlobalConfiguration.Configuration.Formatters.XmlFormatter;
// Use XmlSerializer for instances of type "Product":
mytestxml.SetSerializer<Product>(new XmlSerializer(typeof(MyTestCustomer)));
// Use XmlSerializer for instances of type "Product":
mytestxml.SetSerializer<Product>(new XmlSerializer(typeof(MyTestCustomer)));
51) What is
“Under-Posting” and “Over-Posting” in Web API?
·
“Under-Posting” - When client leaves out some of the properties while binding
then it’s called under – posting.
·
“Over-Posting” – If the client sends more data than expected in binding then
it’s called over-posting.
52) How to handle
validation errors in Web API?
Web API will not
return error to client automatically on validation failure. So its controller’s
duty to check the model state and response to that. We can create a custom
action filter for handling the same.
53) Give an example of
creating custom action filter in Web API?
Below is the sample code for creating custom
action filter –
public class MyCustomModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
//Code goes here
}
}
}
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
//Code goes here
}
}
}
In case validation fails here it returns HTTP
response which contains validation errors.
54) How to apply custom
action filter in WebAPI.config?
Add a new action filter in “Register” method
as shown –
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new MyCustomModelAttribute());
// ...
}
}
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new MyCustomModelAttribute());
// ...
}
}
55) How to set the custom
action filter in action methods in Web API?
Below is the sample code of action with custom
action filter –
public class MyCustomerTestController : ApiController
{
[MyCustomModelAttribute]
public HttpResponseMessage Post(MyTestCustomer customer)
{
// ...
}
}
{
[MyCustomModelAttribute]
public HttpResponseMessage Post(MyTestCustomer customer)
{
// ...
}
}
56) What is BSON in Web
API?
It’s is a binary
serialization format. “BSON” stands for “Binary JSON”. BSON serializes objects
to key-value pair as in JSON. Its light weight and its fast in encode/decode.
57) How to enable BSON in
server?
Add “BsonMediaTypeFormatter” in WebAPI.config
as shown below
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.Add(new BsonMediaTypeFormatter());
// Other Web API configuration goes here
}
}
{
public static void Register(HttpConfiguration config)
{
config.Formatters.Add(new BsonMediaTypeFormatter());
// Other Web API configuration goes here
}
}
58) How parameter binding works in Web API?
Below are the rules followed by WebAPI before
binding parameters –
·
If it is simple
parameters like – bool,int, double etc. then value will be obtained from the
URL.
·
Value read from
message body in case of complex types.
59) Why to use “FromUri”
in Web API?
In Web API to read complex types from URL we will use “FromUri” attribute to the parameter in action method. Eg:
public MyValuesController : ApiController
{
public HttpResponseMessage Get([FromUri] MyCustomer c) { ... }
}
{
public HttpResponseMessage Get([FromUri] MyCustomer c) { ... }
}
60) Why to use “FromBody”
in Web API?
This attribute is used
to force Web API to read the simple type from message body. “FromBody” attribute is along with parameter. Eg:
Public HttpResponseMessage
Post([FromBody] int customerid, [FromBody] string
customername) { ... }
61) Why to use
“IValueprovider” interface in Web API?
This interface is used to implement custom
value provider.