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:
·
In Application_Start()
method of Global.asax file
·
WebApiConfig.Register(GlobalConfiguration.Configuration);
·
In Register(HttpConfiguration
config) method pf WebApiConfig.cs
file
·
config.Routes.MapHttpRoute(
name: “RouteName”,
routeTemplate: “api/{controller}/{id}
defaults: new { id = RouteParameter.Optional}
);
4.
List out
the differences between WCF and Web API
·
WCF is framework build for building or
developing service oriented applications.
·
WCF can be consumed by clients which can understand XML
·
WCF supports
multiple protocols like: HTTP, TCP, Named Pipes etc
·
Web API is a framework which helps us to build/develop HTTP services
·
Web API is an open source platform.
·
Web API 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
·
In WCF Rest, we need to use WebHttpBinding to be enabled for WCF Rest. For each method there
has to be attributes like, WebGet, WebInvoke for GET and POST verbs
respectively.
·
In Web API, we can use full features of HTTP. Web API can be hosted in IIS or in
application
7.
List out
differences between MVC and Web API
·
MVC is used
to create a web app, in which we can build web pages.
·
For JSON, it will return JSONResult from action method.
·
All requests
are mapped to the respective action
methods.
·
Web API 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
·
OData
·
Filters
·
Self-Hosting
·
Routing
·
Model Bindings
9.
Can we unit
test Web API
·
Yes, we can
unit test the Web API using Fiddler
tool.
·
In Compose Tab -> Enter Request Headers ->
Enter the Request Body and execute
10.
Can we
return view from Web API
·
No. We cannot return view from Web API
11.
How we can
restrict access to methods with specific HTTP verbs
·
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 SomeAction() {
//your code
}
12.
Can we use
Web API with ASP.NET Web Forms
·
Yes. We can
use Web API with ASP.NET Webforms as below:
·
Add new controller for Web API inheriting ApiController
·
Add routing table in Application_Start() method in Global.asax
·
Make a AJAX call to Web API actions
13.
Explain how
to give alias name for action methods in Web API
·
Using attribute ActionName we can give alias name for Web API actions.
[HttpPost]
[ActionName(“SomeActionName”)]
public void SomeAction() {
//your code
}
14.
What is the
difference between MVC Routing and Web API Routing
·
There should
be at least one route defined for
MVC and Web API to run
application.
·
In Web API routeTemplate, “api/” is at the beginning which makes it distinct from MVC
routing.
·
In Web API action
parameter is not mandatory but it can be a part of routing
15.
Explain
about the new features added in Web API 2.0 version
·
OWIN
·
Attribute Routing
·
External Authentication
·
Web API OData
16.
How can we
pass multiple complex types in Web API
·
Using ArrayList
·
Newtonsoft JArray
ArrayList paramList = new ArrayList();
ComplexType1 c1 = new ComplexType1 {key
= value, key = “value”};
ComplexType1 c2 = new ComplexType2 {key
= value, key = “value”};
paramList.Add(c1);
paramList.Add(p2);
17.
How to
enable tracing in Web API
·
Add
config.EnableSystemDiagnosticsTracing(); in Register() method of WebAPIConfig.cs file
18.
Explain how
Web API tracing works
·
Tracing in Web API done in facade 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
19.
Explain
Exception Filters
·
Exception filters will be executed whenever controller methods (actions) throws an unhandled exception.
·
Exception filters will implement IExceptionFilter interface or we can override
the OnException(HttpActionExecutedContext
context) method of ExceptionFilterAttribute
class
20.
How we can
handle errors in Web API
·
HttpResponseException
·
Exception Filters
·
Registering Exception Filters
·
HttpError
21.
Explain how
we can handle error from HttpResponseException
·
This returns the HTTP status code what you
specify in the constructor.
public ClassName MethodName(int id) {
ClassName obj = repository.Get(id);
if (obj == null) {
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return obj;
}
22.
How to
register Web API exception filters
·
From Action
·
From Controller
·
Global registration
23.
Code to
register exception filters from action
[NotImplExceptionFilter]
public void MethodName() {
//Your code goes here
}
24.
Code to
register exception filters from controller
[NotImplExceptionFilter]
public class ClassNameController : ApiController {
//Your code goes here
}
25.
Code to
register exception filters globally
GlobalConfiguration.Configuration.Filters.Add(new NameSpace.NotImplExceptionFilterAttributeClass());
26.
How to
handle error using HttpError
·
HttpError will be used to throw the error info in response body.
·
CreateErrorResponse()
extension method is used, which is defined in HttpRequestMessageExtensions
string message = string.Format(“Record with Id = {0} not found”, id);
return
Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
27.
How to set
the Error Result in Web API
HttpResponseMessage objResponse = new
HttpResponseMessage(HttpStatusCode.Unauthorized);
objResponse.RequestMessage = Request;
objResponse.ReasonPhrase = ReasonPhrase;
28.
Explain
ASP.NET Identity
·
This is the new membership system for ASP.NET which allows to add features of login in our application. Below are the list of
features supported by ASP.NET Identity:
·
One ASP.NET Identity System
·
Persistence Control
29.
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
30.
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
31.
How to set
the Authentication filters in Web API
·
Authentication filters can be applied at the controller or action level.
·
Decorate controller class by [Authorize] attribute
·
Decorate authentication filter attribute IdentityBasicAuthentication over
controller/ action where we have to set the authentication filter
32.
Explain
method AuthenticateAsync() in Web API
·
AuthenticateAsync() method authenticates the
request by validating credentials in the request, if present and create IPrincipal and will set on request.
Task
AuthenticateAsync(HttpAuthenticationContext objContext,
CancellationToken objCancellationToken)
33.
Explain
method ChallengeAsync() in Web API
·
ChallengeAsync() method is used to add authentication challenges to
response.
Task ChallengeAsync( HttpAuthenticationChallengeContext objContext, CancellationToken mytestcancellationToken)
34.
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. E.g.:
Image/Png, Text/HTML, Application/Json
35.
Explain
Media Formatters in Web API
·
Media Formatters in Web API can be used to read the CLR object from our HTTP body
and write CLR objects of message body of
HTTP
36.
How to
serialize read-only properties
·
By setting
DataContractSerializerSettings.SerializeReadOnlyTypes = true
37.
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;
38.
How to
indent the JSON in web API
var mytestjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting
= Newtonsoft.Json.Formatting.Indented;
39.
How to JSON
serialize anonymous and weakly types objects
·
Using Newtonsoft.Json.Linq.JObject
we can serialize and deserialize weakly typed objects
40.
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 don’t
want to serialize the property then decorate the property with this
attribute
41.
How to
write indented XML in Web API
·
To write the indented xml set Indent property to true
42.
How to set
Per-Type xml serializer
·
We can use method SetSerializer() as below:
·
var objXml
= GlobalConfiguration.Configuration.Formatters.XmlFormatter;
·
// Use XmlSerializer for instances of
type “Product”
·
objXml.SetSerializer<Product>(new XmlSerializer(typeof(ClassName)));
43.
What is Under-Posting
and Over-Posting in Web API
·
When client
leaves out some of the properties while binding then it’s called under-posting
·
If the
client sends more data than expected in binding then it’s called over-posting
44.
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 by creating a custom action filter
public class ClassCustomAction : ActionFilterAttribute {
public override void
OnActionExecuting(HttpActionContext actionContext) {
if (actionContext.ModelState.IsValid ==
false) {
//Code goes here }}}
·
In case validation fails here it returns HTTP response which contains validation errors.
45.
How to
apply custom action filter in WebAPI.config
·
Add a new action filter in Register() method as:
public static class WebApiConfig {
public static void
Register(HttpConfiguration config) {
config.Filters.Add(new ClassCustomAction()); }}
46.
Methods in
Custom Action Filter
·
OnActionExecuting(ActionExecutingContext
filterContext): Just before the action method is called.
·
OnActionExecuted(ActionExecutedContext
filterContext): After the action method is called and before
the result is executed (before view render).
·
OnResultExecuting(ResultExecutingContext
filterContext): Just before the result is executed (before view
render).
·
OnResultExecuted(ResultExecutedContext
filterContext): After the result is executed (after the view is
rendered)
47.
How to set
the custom action filter in action methods in Web API
public class TestController : ApiController {
[ClassCustomAction]
public void Get() {}}
48.
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
·
Add BsonMediaTypeFormatter
in WebAPI.config to enable it
public static class WebApiConfig {
public static void
Register(HttpConfiguration config) {
config.Formatters.Add(new
BsonMediaTypeFormatter()); }}
49.
How
parameter binding works in Web API
·
If it is simple parameters like, bool, int,
double then value will be obtained from the URL.
·
Value read from message body in case of complex
types.
50.
Why to use
“FromUri” in Web API
·
To read
complex types from URL we use FromUri attribute in action method.
public HttpResponseMessage Get([FromUri]
ComplexType c) { … }
51.
Why to use
“FromBody” in Web API
·
To read the
simple type from message body we use FromBody attribute
public HttpResponseMessage Post([FromBody]
int customerid) { … }
52.
Why to use IValueprovider
interface in Web API
·
This interface
is used to implement custom value
provider.
53.
What is
OutputCache filter
·
This action filter caches the output of a
controller action for a specified amount of time.
·
Decorate action with [OutputCache(Duration=10)] attribute, to get cached output/
result till 10 seconds
54.
Web API
versioning
·
APIs only need to be up-versioned when a breaking change is made
·
REST doesn’t provide for any specific versioning
guidelines but the more commonly used approaches fall into four categories:
·
URI Versioning: straightforward and most commonly used approach. Using Attribute Routing we
have different URL patterns for different controller
·
Web API provides a
class DefaultHttpControllerSelector which has a method SelectController()
that selects the controller based on the information it has in the URI.
·
Using QueryString
parameter: simple because everything
is dependent on the query string parameter only. We have to pass version
number in query string and in SelectController()
method use this parameter to decide the controller
·
Using Custom Request Header: we pass a custom header for version number in request header and read
that header in SelectController() method to decide the controller
·
Using Accept
header: The Accept header tells the
server in what file format the browser wants the data. These file formats
are more commonly called as MIME-types.
MIME stands for Multipurpose Internet
Mail Extensions. Instead of creating a custom header just for versioning
purpose, we can use the standard Accept header. We can add parameters to the
Accept header to send any additional data like version of the service
·
override HttpControllerDescriptor SelectController(HttpRequestMessage request)