Iteanz Interview Questions | Latest Technologies Interview Questions

ASP .Net Web API Essentials using C# Interview Questions

Written by Rupa.R | Sep 9, 2022 11:52:11 AM

Q1. What is Web API?

Ans: It is a framework which helps us to build/develop HTTP services. So there will a client server communication using HTTP protocol.

Q2. What is Representational state transfer or REST?

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.

Q3. Explain Web API Routing?

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}
};

Q4. List out the differences between WCF and Web API?

Ans:

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.

Q5. What are the advantages of using REST in 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.

Q6. Difference between WCF Rest and Web API?

Ans:

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.

Q7. List out differences between MVC and Web API?

Ans: Below are some of the differences between MVC and Web API

MVC

  • MVCis used to create a web app, in which we can build web pages.
  • For JSONit 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.

Q8. What are the advantages of Web API?

Ans: Below are the list of support given by Web API –

  • OData
  • Filters
  • Content Negotiation
  • Self Hosting
  • Routing
  • Model Bindings

Q9. Can we unit test Web API?

Ans: Yes we can unit test Web API.

Q10. How to 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

Q11. Can we return view from Web API?

Ans: No. We cannot return view from Web API.

Q12. 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);
}

Q13. Can we use Web API with ASP.NET Web Forms?

Ans: Yes. We can use Web API with ASP.NET Webforms.

Q14. List out the steps to be made for Web API to work in Web Forms?

Ans: Below are the steps to be followed –

  1. Creating new controller for Web API.
  2. Adding routing table to “Application_Start” method in asax
  3. Make a AJAX call to Web API actions.

Q15. Explain how to give alias name for action methods in Web API?

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);
}

Q16. What is the difference between MVC Routing and Web API Routing?

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.

Q17. Explain Exception Filters?

Ans: Exception filters will be executed whenever controller methods (actions) throws an exception which is unhandled. Exception filters will implement “IExceptionFilter” interface.

Q18. Explain about the new features added in Web API 2.0 version?

Ans: Below are the list of features introduced in Web API 2.0 –

  • OWIN
  • Attribute Routing
  • External Authentication
  • Web API OData

Q19. How can we pass multiple complex types in Web API?

Ans: Below are the methods to pass the complex types in Web API –

  1. Using ArrayList
  2. Newtonsoft JArray

Q20. Write a code snippet for passing arraylist 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);

Q21. Give an example of Web API Routing?

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 }
);

Q22. Give an example of MVC Routing?

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
}
);

Q23. How we can handle errors in Web API?

Ans: Below are the list of classes which can be used for error handling -

  • HttpResponseException
  • Exception Filters
  • Registering Exception Filters
  • HttpError

Q24. Explain how we can handle error from “HttpResponseException”?

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;
}

Q25. How to register Web API exception filters?

Ans: Below are the options to register Web API exception filters –

  • From Action
  • From Controller
  • Global registration

Q26. Write a code snippet to register exception filters from action?

Ans: Below is the code snippet for registering exception filters from action –

[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}

Q27. Write a code snippet to register exception filters from controller?

Ans: Below is the code snippet for registering exception filters from controller –

[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}

Q28. Write a code snippet to register exception filters globally?

Ans: Below is the code snippet for registering exception filters globally –

Global Configuration. Configuration. Filters.Add( new My Test Customer Store.Not Impl Exception Filter Attribute());

Q29. How to handle error using HttpError?

Ans: Http Error will be used to throw the error info in response body. “Create Error Response” method is used along with this, which is an extension method defined in “Http Request Message Extensions”.

Q30. Write a code snippet to show how we can return 404 error from HttpError?

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);

Q31. How to enable tracing in Web API?

Ans: To enable tracing place below code in –“Register” method of WebAPIConfig.cs file.

config.EnableSystemDiagnosticsTracing();

Q32. Explain how Web API tracing works?

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.

Q33. Can we unit test Web API?

Ans: Yes we can unit test Web API.

Q34. Explain Authentication in 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.

Q35. Explain ASP.NET Identity?

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 –

  • One ASP.NET Identity System
  • Persistence Control

Q36. What are Authentication Filters 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.

Q37. How to set the Authentication filters in Web API?

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.

Q38. Explain method – “AuthenticateAsync” in Web API?

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
)

Q39. How to set the Error Result in Web API?

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;

Q40. Explain method – “ChallengeAsync” in Web API?

Ans: “ChallengeAsync” method is used to add authentication challenges to response. Below is the method signature –

Task ChallengeAsync(
HttpAuthenticationChallengeContext mytestcontext,
CancellationToken mytestcancellationToken
)

Q41. What are media types?

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.

Q42. List out few media types of HTTP?

Ans: Below are the list of media types –

  • Image/Png
  • Text/HTML
  • Application/Json

Q43. Explain Media Formatters in Web API?

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.

Q44. How to serialize read-only properties?

Ans: Read-Only properties can be serialized in Web API by setting the value “true” to the property –

“SerializeReadOnlyTypes” of class – “DataContractSerializerSettings”.

Q45. How to get Microsoft JSON date format ?

Ans: Use “DateFormatHandling” property in serializer settings as below –

var myjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
myjson.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;

Q46. How to indent the JSON in web API?

Ans: Below is the code snippet to make JSON indenting –

var mytestjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

Q47. How to JSON serialize anonymous and weakly types objects?

Ans: Using “Newtonsoft.Json.Linq.JObject” we can serialize and deserialize weakly typed objects.

Q48. What is the use of “IgnoreDataMember” in Web API?

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.

Q49. How to write indented XML in Web API?

Ans: To write the indented xml set “Indent” property to true.

Q50. How to set Per-Type xml serializer?

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)));

Q51. What is “Under-Posting” and “Over-Posting” in Web API?

Ans:

  • “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.

Q52. How to handle validation errors in Web API?

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.

Q53. Give an example of creating custom action filter in Web API?

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.

Q54. How to apply custom action filter in WebAPI.config?

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());
// ...
}
}

Q55. How to set the custom action filter in action methods in Web API?

Ans: Below is the sample code of action with custom action filter –

public class MyCustomerTestController : ApiController
{
[MyCustomModelAttribute]
public HttpResponseMessage Post(MyTestCustomer customer)
{
// ...
}
}

Q56. What is BSON in Web API?

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.

Q57. How to enable BSON in server?

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
}
}

Q58. How parameter binding works in Web API?

Ans: 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.

Q59. Why to use “FromUri” in Web API?

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) { ... }
}

Q60. Why to use “FromBody” in Web API?

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) { ... }

Q61. Why to use “IValueprovider” interface in Web API?

Ans: This interface is used to implement custom value provider.