YouTube Icon

Interview Questions.

ASP.Net Web API Essentials using C# Interview Questions - Jul 17, 2022

fluid

ASP.Net Web API Essentials using C# Interview Questions

Q1. What is Web API?

Ans: It is a framework which enables us to construct/increase HTTP offerings. So there'll a customer server verbal exchange the use of HTTP protocol.

Q2. What is Representational state switch or REST?

Ans: REST is architectural fashion, which has described tips for creating offerings which might be 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 sample matching as we've got in MVC. These routes gets registered in Route Tables. Below is the pattern path 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 construct for building or growing carrier oriented programs.

WCF may be consumed by way of clients that could understand XML.

WCF helps protocols like – HTTP, TCP, Named Pipes and many others.

Web API

It is a framework which allows us to construct/broaden HTTP services

Web API is an open source platform.

It helps most of the MVC functions which maintain Web API over WCF.

Q5. What are the blessings of using REST in Web API?

Ans: REST usually used to make less facts transfers between customer and server which makes REST a super for the usage of it in mobile apps. Web API helps HTTP protocol thereby it reintroduces the old way of HTTP verbs for communique.

Q6. Difference between WCF Rest and Web API?

Ans:

WCF Rest

“WebHttpBinding” to be enabled for WCF Rest.

For every method there has to be attributes like – “WebGet” and “WebInvoke”

For GET and POST verbs respectively.

Web API

Unlike WCF Rest we will use full capabilities of HTTP in Web API.

Web API can be hosted in IIS or in software.

Q7. List out variations among MVC and Web API?

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

MVC

MVCis used to create a web app, wherein we are able to construct net pages.

For JSONit will go back JSONResult from motion technique.

All requests are mapped to the respective action strategies.

Web API

This is used to create a carrier the usage of HTTP verbs.

This returns XML or JSON to customer.

All requests are mapped to actions the use of HTTP verbs.

Q8. What are the advantages of Web API?

Ans: Below are the list of guide given via Web API –

OData

Filters

Content Negotiation

Self Hosting

Routing

Model Bindings

Q9. Can we unit test Web API?

Ans: Yes we will unit test Web API.

Q10. How to unit check 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 go back view from Web API?

Ans: No. We can not go back view from Web API.

Q12. How we can restrict get entry to to strategies with unique HTTP verbs in Web API?

Attribute programming is used for this capability. Web API will support to limit get entry to of calling techniques with precise HTTP verbs. We can outline HTTP verbs as attribute over approach 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 –

Creating new controller for Web API.

Adding routing desk to “Application_Start” method in asax

Make a AJAX name to Web API actions.

Q15. Explain a way to supply alias name for motion strategies in Web API?

Ans: Using attribute “ActionName” we are able to supply alias call for Web API moves. Eg:

[HttpPost]

[ActionName("AliasTestAction")]

public void UpdateTestCustomer(Customer c)

TestCustomerRepository.AddCustomer(c);

 

HubSpot Video
 

Q16. What is the distinction among MVC Routing and Web API Routing?

Ans: There need to be atleast one route described for MVC and Web API to run MVC and Web API application respectively. In Web API pattern we are able to locate “api/” at the beginning which makes it awesome from MVC routing. In Web API routing “action” parameter isn't always obligatory however it could be part of routing.

Q17. Explain Exception Filters?

Ans: Exception filters may be performed on every occasion controller methods (movements) throws an exception which is unhandled. Exception filters will put into effect “IExceptionFilter” interface.

Q18. Explain about the new functions delivered in Web API 2.0 model?

Ans: Below are the listing of features delivered in Web API 2.0 –

OWIN

Attribute Routing

External Authentication

Web API OData

Q19. How are we able to pass a couple of complicated sorts in Web API?

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

Using ArrayList

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 instance of Web API Routing?

Ans: Below is the pattern code snippet to expose Web API Routing –

config.Routes.MapHttpRoute(

call: "MyRoute",//path name

routeTemplate: "api/controller/movement/identification",//as you could see "api" is at the beginning.

Defaults: new  id = RouteParameter.Optional 

);

Q22. Give an instance of MVC Routing?

Ans: Below is the sample code snippet to show MVC Routing –

routes.MapRoute(

name: "MyRoute", //route name

url: "controller/motion/id", //path sample

defaults: new

controller = "a4academicsController",

action = "a4academicsAction",

id = UrlParameter.Optional

);

Q23. How we are able to cope with errors in Web API?

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

HttpResponseException

Exception Filters

Registering Exception Filters

HttpError

Q24. Explain how we are able to deal with mistakes from “HttpResponseException”?

Ans: This returns the HTTP reputation code what you specify within the constructor. Eg :

public TestClass MyTestAction(int identity)

TestClass c = repository.Get(identification);

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 check in exception filters from action?

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

[NotImplExceptionFilter]

public TestCustomer GetMyTestCustomer(int custid)

//Your code is going right 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 right here

 

Q28. Write a code snippet to sign in exception filters globally?

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

GlobalConfiguration.Configuration.Filters.Add( new MyTestCustomerStore.NotImplExceptionFilterAttribute());

Q29. How to address mistakes using HttpError?

Ans: HttpError might be used to throw the mistake information in response frame. “CreateErrorResponse” method is used in conjunction with this, that's an extension approach defined in “HttpRequestMessageExtensions”.

Q30. Write a code snippet to expose how we will go back 404 blunders from HttpError?

Ans: Below is the code snippet for returning 404 error from HttpError –

string message = string.Format("TestCustomer identification = 0 no longer observed", customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

Q31. How to allow tracing in Web API?

Ans: To enable tracing region under code in –“Register” technique of WebAPIConfig.Cs record.

Config.EnableSystemDiagnosticsTracing();

Q32. Explain how Web API tracing works?

Ans: Tracing in Web API finished in façade sample i.E, while tracing for Web API is enabled, Web API will wrap one of a kind parts of request pipeline with training, which plays trace calls.

Q33. Can we unit take a look at Web API?

Ans: Yes we can unit check Web API.

Q34. Explain Authentication in Web API?

Ans: Web API authentication will manifest in host. In case of IIS it makes use of Http Modules for authentication or we can write custom Http Modules. When host is used for authentication it used to create foremost, which constitute safety context of the application.

Q35. Explain ASP.NET Identity?

Ans: This is the new membership machine for ASP.NET. This lets in to feature capabilities of login in our software.

Below are the list of features supported through 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 movements or controllers. So this manner our application can guide diverse authentication mechanisms.

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

Ans: Authentication filters may be carried out at the controller or action degree. Decorate characteristic – "IdentityBasicAuthentication” over controller wherein we need to set the authentication filter out.

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

Ans: “AuthenticateAsync” method will create “IPrincipal” and could set on request. Below is the pattern code snippet for “AuthenticateAsync” –

Task AuthenticateAsync(

HttpAuthenticationContext mytestcontext,

CancellationToken mytestcancellationToken

)

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

Ans: Below is the pattern code to reveal how to set error bring about Web API –

HttpResponseMessage myresponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);

myresponse.RequestMessage = Request;

myresponse.ReasonPhrase = ReasonPhrase;

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

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

Task ChallengeAsync(

HttpAuthenticationChallengeContext mytestcontext,

CancellationToken mytestcancellationToken

)

Q41. What are media sorts?

Ans: It is likewise called MIME, that's used to perceive the information . In Html, media types is used to describe message layout within the body.

Q42. List out few media kinds of HTTP?

Ans: Below are the list of media kinds –

Image/Png

Text/HTML

Application/Json

Q43. Explain Media Formatters in Web API?

Ans: Media Formatters in Web API may be used to study the CLR item from our HTTP frame and Media formatters are also used for writing CLR objects of message frame of HTTP.

Q44. How to serialize study-most effective homes?

Ans: Read-Only homes may be serialized in Web API by setting the value “authentic” to the property –

“SerializeReadOnlyTypes” of class – “DataContractSerializerSettings”.

Q45. How to get Microsoft JSON date format ?

Ans: Use “DateFormatHandling” assets 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 net 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 kinds 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 houses are public then the ones may be serialized and deserialized, if we does no longer need to serialize the assets then decorate the property with this characteristic.

Q49. How to write down indented XML in Web API?

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

Q50. How to set Per-Type xml serializer?

Ans: We can use technique – “SetSerializer”. Below is the sample code snippet for the use of 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 patron leaves out a number of the homes while binding then it’s called underneath – posting.

“Over-Posting” – If the customer sends more facts than predicted in binding then it’s called over-posting.

Q52. How to deal with validation mistakes in Web API?

Ans: Web API will not return error to consumer routinely on validation failure. So its controller’s duty to check the version country and response to that. We can create a custom action filter for dealing with the equal.

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

Ans: Below is the sample code for growing custom action filter –

public magnificence MyCustomModelAttribute : ActionFilterAttribute

public override void OnActionExecuting(HttpActionContext actionContext)

if (actionContext.ModelState.IsValid == false)

//Code goes here

 

In case validation fails right here it returns HTTP response which contains validation mistakes.

Q54. How to use custom motion clear out in WebAPI.Config?

Ans: Add a brand new motion filter in “Register” approach as shown -

public static elegance WebApiConfig

public static void Register(HttpConfiguration config)

config.Filters.Add(new MyCustomModelAttribute());

// ...

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

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

public elegance MyCustomerTestController : ApiController

[MyCustomModelAttribute]

public HttpResponseMessage Post(MyTestCustomer consumer)

// ...

Q56. What is BSON in Web API?

Ans: It’s is a binary serialization format. “BSON” stands for “Binary JSON”. BSON serializes gadgets to key-cost 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 proven below

public static elegance WebApiConfig

public static void Register(HttpConfiguration config)

config.Formatters.Add(new BsonMediaTypeFormatter());

// Other Web API configuration is going here

Q58. How parameter binding works in Web API?

Ans: Below are the regulations accompanied by way of WebAPI earlier than binding parameters –

If it is simple parameters like – bool,int, double etc. Then cost could be obtained from the URL.

Value examine from message body in case of complicated types.

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

Ans: In Web API to read complicated types from URL we are able to use “FromUri” characteristic to the parameter in motion approach. Eg:

public MyValuesController : ApiController

public HttpResponseMessage Get([FromUri] MyCustomer c)  ... 

 

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

Ans: This attribute is used to force Web API to read the simple kind from message body. “FromBody” characteristic 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 enforce custom fee provider.




CFG