Ans: It is a framework which helps us to build/develop HTTP services. So there will a client server communication using HTTP protocol.
Ans: 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.
Ans: 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}
};
Ans:
WCF
Web API
Ans: 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.
Ans:
WCF Rest
Web API
Ans: Below are some of the differences between MVC and Web API
MVC
Web API
Ans: Below are the list of support given by Web API –
Ans: Yes we can unit test Web API.
Ans: 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
Ans: No. We cannot return view from 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);
}
Ans: Yes. We can use Web API with ASP.NET Webforms.
Ans: Below are the steps to be followed –
Ans: Using attribute “ActionName” we can give alias name for Web API actions. Eg:
[HttpPost]
[ActionName("AliasTestAction")]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
Ans: 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.
Ans: Exception filters will be executed whenever controller methods (actions) throws an exception which is unhandled. Exception filters will implement “IExceptionFilter” interface.
Ans: Below are the list of features introduced in Web API 2.0 –
Ans: Below are the methods to pass the complex types in Web API –
Ans: 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);
Ans: 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 }
);
Ans: 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
}
);
Ans: Below are the list of classes which can be used for error handling -
Ans: 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;
}
Ans: Below are the options to register Web API exception filters –
Ans: Below is the code snippet for registering exception filters from action –
[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}
Ans: Below is the code snippet for registering exception filters from controller –
[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}
Ans: Below is the code snippet for registering exception filters globally –
GlobalConfiguration.Configuration.Filters.Add( new MyTestCustomerStore.NotImplExceptionFilterAttribute());
Ans: 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”.
Ans: 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);
Ans: To enable tracing place below code in –“Register” method of WebAPIConfig.cs file.
config.EnableSystemDiagnosticsTracing();
Ans: 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.
Ans: Yes we can unit test Web API.
Ans: 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.
Ans: This is the new membership system for ASP.NET. This allows to add features of login in our application.
Below are the list of features supported by ASP.NET Identity in Web API –
Ans: Authentication Filter will let you set the authentication scheme for actions or controllers. So this way our application can support various authentication mechanisms.
Ans: Authentication filters can be applied at the controller or action level. Decorate attribute – "IdentityBasicAuthentication” over controller where we have to set the authentication filter.
Ans: “AuthenticateAsync” method will create “IPrincipal” and will set on request. Below is the sample code snippet for “AuthenticateAsync” –
Task AuthenticateAsync(
HttpAuthenticationContext mytestcontext,
CancellationToken mytestcancellationToken
)
Ans: 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;
Ans: “ChallengeAsync” method is used to add authentication challenges to response. Below is the method signature –
Task ChallengeAsync(
HttpAuthenticationChallengeContext mytestcontext,
CancellationToken mytestcancellationToken
)
Ans: 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.
Ans: Below are the list of media types –
Ans: 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.
Ans: Read-Only properties can be serialized in Web API by setting the value “true” to the property –
“SerializeReadOnlyTypes” of class – “DataContractSerializerSettings”.
Ans: Use “DateFormatHandling” property in serializer settings as below –
var myjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
myjson.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
Ans: Below is the code snippet to make JSON indenting –
var mytestjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
Ans: Using “Newtonsoft.Json.Linq.JObject” we can serialize and deserialize weakly typed objects.
Ans: 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.
Ans: To write the indented xml set “Indent” property to true.
Ans: 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)));
Ans:
Ans: 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.
Ans: Below is the sample code for creating custom action filter –
public class MyCustomModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
//Code goes here
}
}
}
In case validation fails here it returns HTTP response which contains validation errors.
Ans: 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());
// ...
}
}
Ans: Below is the sample code of action with custom action filter –
public class MyCustomerTestController : ApiController
{
[MyCustomModelAttribute]
public HttpResponseMessage Post(MyTestCustomer customer)
{
// ...
}
}
Ans: 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.
Ans: 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
}
}
Ans: Below are the rules followed by WebAPI before binding parameters –
Ans: 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) { ... }
}
Ans: 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) { ... }
Ans: This interface is used to implement custom value provider.
Related Interview Questions...
.Net Interview Questions and Answers
VB.NET Interview Questions and Answers
ASP.NET MVC Interview Questions and Answers
ASP.NET Interview Questions and Answers For Experienced
ASP.NET Interview Questions and Answers