Web API is a vital software programming interface that allows internet providers over a broad vary of browsers and units reminiscent of tablets, cellphones, and so forth. It is of serious significance for its light-weight and less complicated providers and can be utilized as a standalone internet service software.
If you’re a pupil of Web API or knowledgeable who’s creating their competence on this framework, you already know the significance of getting a dependable useful resource of Web API interview questions. As the main focus of Web API is sensible, any assortment of questions has to deal with the appliance of Web API in sensible eventualities. These interview questions also can assist you to put together on your dream job on this area. Check out free API programs.
Let us perceive extra about Web API by delving into these Web API Interview Questions, which can assist you to throughout a job interview or improve your total data and understanding of this topic.
Web API Interview Questions
1. What is ASP.Net Web API?
A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP-based providers. Clients coping with cellular functions and internet browsers can eat Web API.
2. What are the variations between Web API and WCF REST API?
A: Web API is appropriate for HTTP-based providers, whereas WCF REST API is right for Message queues, one-way messaging, and duplex communication. WEB API helps any media format, even XML and JSON, whereas WCF helps SOAP and XML codecs. ASP.Net Web API is right for constructing HTTP providers, whereas WCF is ideal for creating service-oriented functions. To run Web API, there is no such thing as a configuration required, whereas within the case of WCF, numerous configuration is required to run it.
3. What are some great benefits of utilizing ASP.Net Web API?
A: The benefits of utilizing ASP.Net Web API are talked about beneath:
- It completes help for routing
- Is works as HTTP utilizing normal HTTP verbs reminiscent of GET, DELETE, POST, PUT, to call a number of, for all CRUD operations
- It will be hosted in IIS in addition to self-host exterior of IIS
- It helps OData
- It helps validation and mannequin binding
- The response is generated in XML or JSON format by utilizing MediaTypeFormatter
4. What are the a number of return sorts in ASP.Net Web API?
A: The varied return sorts in ASP.Net Web API are:
- IHttpActionResult
- HttpResponseMessage
- Void
- Other Type – string, int, or different entity sorts.
5. What is ASP.Net Web API routing?
A: It is the method that determines the motion and controller that needs to be known as.
The methods to include routing in Web API embrace:
- Attribute primarily based routing
- Convention primarily based routing
6. What are Media sort formatters in Web API?
A: The Media sort formatter in Web API embrace:
- MediaTypeFormatter – It is the bottom class that helps to deal with serializing and deserializing strongly-typed objects.
- BefferedMediaTypeFormatter – It signifies a helper class to permit asynchronous formatter on high of the asynchronous formatter infrastructure.
7. What is the CORS difficulty in Web API?
A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin restriction for JavaScript. Same-origin means JavaScript solely makes AAJAX name for internet pages throughout the same-origin.
You have to put in the CORS nuget package deal by utilizing Package Manager Console to allow CORS in Web API.
Open WebAPIConfig.cs file
add config.EnableCors();
Add EnableCors attribute to the Controller class and outline the origin.
[EnableCors(origins: “”, headers: “*”, methods: “*”)].
8. How to safe an ASP.Net Web API?
A: To safe an ASP.Net Web API, we have to management the Web API and determine who can entry the API and who can’t entry it. Web API will be accessed by anybody who is aware of in regards to the URL.
9. What are the variations between HTTP Get and HTTP Post?
A: GET and POST are two necessary verbs of HTTP.
- Parameters of GET are included within the URL; whereas parameters of POST are included within the physique
- GET requests don’t make any adjustments to the server; whereas POST does make adjustments to the server
- A GET request is idempotent; whereas a POST request is non-idempotent
- In a GET request, information is distributed in plain textual content; binary and textual content information are despatched
10. How can Web API be used?
A: Web API can simply be used with ASP.Net Forms. You can add Web API Controller and route in Application Start methodology in Global.asax file.
11.Exception filters in ASP.Net Web API
A: Exception filters in Web API assist in implementing IExceptionFilters interface. They carry out when an motion throws an exception at any level.
12. Do we return Views from ASP.Net Web API?
A: No, it’s not doable as Web API creates an HTTP-based service. It is generally accessible within the MVC software.
13. What is new in ASP.Net Web API 2.0?
A: The options launched in ASP.NET Web API framework v2.0 are:
- Attribute Routing
- External Authentication
- CORS (Cross-Origin Resource Sharing)
- OWIN (Open Web Interface for .NET) Self Hosting
- IHttpActionResult
- Web API Odata
14. How can we restrict entry to strategies with an HTTP verb in Web API?
A: An attribute needs to be added as proven beneath:
[HttpGet]
public HttpResponseMessage Test()
{
HttpResponseMessage response = new HttpResponseMessage();
///
return response;
}
[HttpPost]
public void Save([FromBody]string worth)
{
}
15. How can we be sure that Web API returns information in JSON format solely?
A: To be certain that internet API returns information in JSON format solely, open “WebApiConfig.cs” file in addition to add the beneath line:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/json”))
To be taught JSON format, you can even take up free on-line programs that can assist you to improve your primary abilities about the identical.
16. How to offer Alias identify for an motion methodology in Web API?
A: By including an attribute ActionName, an Alias identify will be supplied:
[ActionName(“InertUserData”)]
// POST api/
public void Post([FromBody]string worth)
{
}
17. How can we deal with errors in Web API?
A: Handling errors or exceptions in Web API will be achieved with the assistance of the next courses –
- Using HttpResponseException –This exception class helps to return the HTTP standing code specified within the exception Constructor.
- Using HttpError – This exception class helps to return significant error code to the shopper as HttpResponseMessage.
- Using Exception filters – Exception filters assist in catching unhandled exceptions or errors generated in Web API and so they can be utilized every time the controller motion methodology throws the unhandled error.
18. How to host Web API?
A: There are two methods how Web API software will be hosted:
- Self Hosting
- IIS Hosting
19. How to eat Web API utilizing HTTPClient?
A: HTTPClient is launched in HTTPClient class for speaking with ASP.Net Web API. This HTTPClient class is used both in a console software or in an MVC software.
20. Explain oData with ASP.Net Web API.
A: OData is the acronym for Open Data Protocol. It is a Rest-based information entry protocol. OData gives a approach to manipulate information by making use of CRUD operations. ASP.Net Web API helps OData V3 and V4.
To use OData in ASP.Net Web API, you would wish an OData package deal. You must run the beneath command within the Package Manager Console.
Install-Package Microsoft.AspNet.Odata
21. Can we eat Web API 2 in C# console software?
A: Yes, Web API 2 will be consumed in Console Application, MVC, Angular JS, or another software.
22. Perform Web API 2 CRUD operation utilizing Entity Framework.
A: CRUD operation will be carried out by utilizing entity framework with Web API.
23. How to allow HTTPs in Web API?
A: ASP.Net Web API runs over HTTP protocol. You can create a category and get a category with AuthorizationFilterAttribute. Now examine if the requested URL has HTTPs.
24. How to implement Basic Authentication in ASP.Net Web API?
A: Basic Authentication in ASP.Net Web API will be applied the place the shopper sends a request with an Authorization header and the phrase Basic. In Basic Authentication, the Authorization header accommodates the phrase Basic adopted by a base 64 encoded string.
The syntax for Basic Authentication –
Authorization: Basic username: password
25. What is Token Based Authentication in Web API?
A: It is an strategy to safe .Net Web API because it authenticates customers by a signed token, additionally known as a token-based strategy.
26. What is content material negotiation in .Net Web API?
A: In ASP.Net Web API, content material negotiation is finished on the server aspect. This helps in figuring out the media sort formatter, particularly when it’s about returning the response to an incoming request.
27. What is ASP.Net identification?
A: ASP.Net identification is the membership administration framework that Microsoft gives. It could be very simply integrated with Web API. This can assist you to construct a safe HTTP service.
28. What is Bearer Authentication in .Net Web API?
A: Bearer authentication is also referred to as Token-based authentication.
29. What is REST?
A: REST stands for Representational State Transfer. This is an architectural sample that helps in exchanging information over a disseminated surroundings.
REST architectural sample treats all of the providers as assets and a shopper can entry these assets by utilizing HTTP protocol strategies which embrace PUT, GET, POST, and DELETE.
30. What is Not REST?
A: The talked about beneath usually are not REST:
- A typical
- A protocol
- 3. A alternative of SOAP
31. What are the variations between REST and SOAP?
A: Here are some variations between REST and SOAP:
SOAP | REST |
---|---|
SOAP stands for Simple Object Access Protocol | REST stands for Representational State Transfer. |
SOAP is a protocol, known as an XML | REST will not be a protocol however you may name it an architectural sample instance which is used for resource-based structure. |
SOAP specifies each stateless in addition to state-full implementation | REST is totally stateless. |
SOAP applies message codecs like XML; | REST doesn’t apply message codecs like XML or JSON. |
To expose the service, SOAP makes use of interfaces and named operations; | REST makes use of URI and strategies like POST, GET, PUT, and DELETE for exposing assets (service). |
32. What are the variations between ASP.NET MVC and ASP.NET Web API?
A: MVC is used to create internet functions that may return views in addition to information, whereas ASP.NET Web API is used to create restful HTTP providers merely, which returns solely information and no view. In MVC, the request is mapped to the actions identify, whereas the request is mapped to the actions primarily based on HTTP verbs in Web API.
33. Is it true that ASP.NET Web API has changed WCF?
A: It will not be true! It is slightly simply one other approach to construct non-SOAP-based providers like plain XML or JSON strings. It comes with further benefits reminiscent of utilizing HTTP’s full options and reaching extra purchasers reminiscent of cellular units, and so forth.
34. Explain media Formatters in Web API 2
A: These are courses which might be liable for response information. The Web API understands the request information format in addition to sends information within the format as anticipated by the purchasers.
35. Which protocol is supported by Web API?
A: The solely protocol supported by Web API is HTTP. Therefore, it may be consumed by a shopper that helps HTTP protocol.
36. What are the similarities between MVC and Web API?
A: Both MVC and Web API are primarily based on the precept of Separation of issues and ideas like controllers, routing, and fashions.
37. What are the variations between MVC and Web API?
A: MVC is used for creating functions that include User interfaces. The Views in MVC are used to develop a User Interface. Web API is used for creating HTTP providers. To fetch information, the Web API strategies are known as by different functions.
38. Who can eat Web API?
A: Web API is consumed by a shopper that helps HTTP verbs reminiscent of DELETE, GET, PUT, and POST. They can fairly simply be consumed by a shopper as Web API providers don’t want any configuration. Web API will be consumed very simply by transportable units.
39. How are Requests mapped to Action strategies in Web API?
A: As Web API makes use of HTTP verbs, a shopper that may eat a Web API that wants methods to name the Web API methodology. A shopper can use the HTTP verbs to name the motion strategies of the Web API.
Take a take a look at the instance given beneath. In order to name a technique like GetWorker, shopper can use a jQuery methodology like:
$.get(“/api/Employees/1”, null, perform(response)
{
$(“#employees”).html(response);
});
Therefore, the strategy identify above has no point out. As another, GetWorker methodology will be known as by utilizing the GET HTTP verb.
The GetWorker methodology will be outlined as:
[HttpGet]
public void GetWorker(int id)
{
StudentRepository.Get(id);
}
As the GetWorker methodology will be seen adorned with the [HttpGet] attribute, completely different verbs to map the completely different HTTP requests have for use:
- HttpGet
- HttpPut
- HttpPost
- HttpDelete
40. Can the HTTP request be mapped to the motion methodology with out utilizing the HTTP attribute?
A: For the motion methodology, there are two methods to map the HTTP request. The first manner is utilizing the trait on the motion methodology. The second manner is naming the strategy that begins with the HTTP verb. Taking for instance, to outline a GET methodology, will be outlined as:
public void GetWorker(int id)
{
StudentRepository.Get(id);
}
As it might begin with GET, the above-mentioned methodology will be routinely mapped with the GET request.
41. How so as to add certificates to a web site?
A: To add the certificates to the web site, you may comply with the steps talked about beneath:
- You must go to run sort command mmc
- Now click on on Ok
- The certificates add window is open now
42. Write a LINQ code for authenticating the consumer?
A: public static bool Login(string UN, string pwd)
{StudentDBEntities college students = new StudentDBEntities()college students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // college students has a couple of desk}
43. How to navigate one other web page in jQuery?
A: utilizing widow.location.href = “~/homw.html”;
44. How to allow SSL to ASP.NET internet?
A: In order to allow SSL to ASP.NET internet, you may click on on mission properties the place you may see this feature.
45. How to say Roles and customers utilizing Authorize attribute in Web API?
// Restrict by Name
[Authorize(Users=”Shiva,Jai”)]
public class ScholarController : ApiController{}
// Restrict by Role[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController{}
46. Can we apply constraints on the route degree?
A: Yes, it may be utilized.
[Route(“students/{id:int}”]
public User GetScholarById(int id) { … }
[Route(“students/{name}”]
public User GetScholarByName(string identify) { … }
You can choose the primary route every time the “id” phase of the URI is an integer. Or else, you may select the second route.
47. How to allow attribute routing?
A: To allow attribute routing, MapHttpAttributeRoutes(); methodology will be known as within the WebApi config file.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not proven.
}
48. How parameters get the worth in Web API?
A: Parameters get worth in Web API within the following manner:
- Request physique
- URI
- Custom Binding
49. Why is the “api/” phase utilized in Web API routing?
A: “api/” phase is used to keep away from collisions with ASP.NET MVC routing
50. Is it doable to have MVC type of routing in Web API?
A: It is feasible to implement MVC type of routing in Web API.
51. Where is the route outlined in Web API?
A: It is positioned within the App_Start listing.
App_Start –> WebApiConfig.cs
routes.MapHttpRoute(
identify: “myroute”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
52. How do you assemble HtmlResponseMessage?
public class TestController : ApiController
A: To assemble HtmlResponseMessage, you may take into account the next manner:
{
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, “value”);
response.Content = new StringContent(“Testing”, Encoding.Unicode);
response.Headers.CacheManagement = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
}
53. What are the default media sorts supported by Web API?
A: The default media sorts which might be supported by Web API are XML, form-urlencoded information, JSON, BSON. The different media sorts supported will be achieved by writing a media formatter.
54. What is the drawback of “Other Return Types” in Web API?
A: The main drawback of “Other Return Types” in Web API is that error codes like 404 errors won’t instantly be returned.
55. What is the namespace for IHttpActionResult return sort in Web API?
A: System.Web.Http.Results namespace
56. Why is Web API necessary?
We have a number of different applied sciences just like Web API but it’s an important and most well-liked over others for a number of causes –
- Web API has probably the most light-weight structure and gives a simple interface for web sites and shopper functions to entry information.
- It makes use of low bandwidth. This makes it ideally suited for even small bandwidth units, for example, smartphones.
- It can create non-SOAP-based HTTP providers.
- It will be consumed by a variety of purchasers together with internet browsers, desktop and cellular functions.
- Web API relies on HTTP which makes it handy to outline, eat or expose utilizing REST-ful providers.
- It matches finest with HTTP verbs for operations reminiscent of Create, Read, Delete or Update.
- Web API is extra helpful from the enterprise viewpoint and finds its functions in UI/UX to extend internet visitors and curiosity in an organization’s providers or merchandise.
- It can help a plethora of textual content and media codecs reminiscent of JSON, XML, and so forth.
- It also can help Open Data (OData) protocol.
- It is most fitted for the MVC sample which makes it ideally suited for knowledgeable builders in that sample.
- It will be simply constructed utilizing applied sciences reminiscent of ASP.NET, JAVA, and so forth.
- It is taken into account the perfect to create resource-oriented providers.
57. Which .NET framework helps Web API?
The .NET framework model supported by Web API consists of model 4.0 and above.
58. Which open-source library is supported by Web API for JSON serialization?
JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API.
59. What are some great benefits of utilizing REST in Web API?
REST provides quite a few benefits in Web API that embrace –
- Lightweight structure and straightforward to make use of
- Offers flexibility
- Allows much less information switch between shopper and server
- Handles varied kinds of information codecs
- Its light-weight structure makes it optimum to be used in cellular functions
- Uses easy HTTP requires inter-machine communication
60. When do we have to select ASP.NET Web API?
We are transferring web-based providers towards cellular functions in right now’s hyper-connected digital world. That means we’d like a light-weight, safe, secure, and appropriate API with these sensible units. The ASP.Net Web API is a framework that fulfils all these necessities for constructing HTTP providers consumed by many purchasers, together with browsers and fashionable units reminiscent of cellphones, tablets, and so forth.
61. What do you perceive by TestApi in Web API?
TestAPi in Web API refers to a utility library that enables builders to create testing instruments in addition to automate assessments for a .NET software.
62. How can we deal with an error utilizing HttpError in Web API?
The HttpError methodology is utilized in Web API to throw the response physique’s error info. One also can use the “CreateErrorResponse” methodology together with this one.
63. Can we eat Web API 2 within the C# console software?
Yes. It is feasible to eat Web API 2 in Console Application, MVC, Angular JS or another software.
64. How to implement Basic Authentication in ASP.Net Web API?
Basic Authentication in ASP.Net Web API is one the place the shopper will ship a request utilizing the phrase Basic with an Authorization header, adopted by a base 64 encoded string.
The syntax for Basic Authentication –
Authorization: Basic username: password
65. Give an instance of the parameter in Web API.
Parameters are utilized in Web API to find out the kind of motion you tackle a selected useful resource. Each parameter consists of a reputation, worth sort and outline that has the power to affect the endpoint response.
You can use the question API to get details about varied entities inside a knowledge supply.
The Get Method employs a number of primitive parameters. For occasion, the Get methodology wants id parameter to get product particulars –
public IHttpActionResult GetProductGrasp(int id)
{
ProductGrasp productMaster = db.ProductMasters.Find(id);
if (productMaster == null)
{
return NotDiscovered();
}
return Ok(productMaster);
}
In the identical manner, the Post methodology would require advanced sort parameters to put up information to the server.
public IHttpActionResult PostProductGrasp(ProductGrasp productMaster)
{
if (!MannequinState.IsLegitimate)
{
return BadRequest(MannequinState);
}
db.ProductMasters.Add(productMaster);
db.SaveModifications();
return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster);
}
Similarly PUT methodology would require primitive information sort instance for id and sophisticated parameter i.e. ProductGrasp class.
if (id != productMaster.id)
{
return BadRequest();
}
db.Entry(productMaster).State = EntityState.Modified;
strive
{
db.SaveModifications();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductMasterExists(id))
{
return NotDiscovered();
}
else
{
throw;
}
}
66. Give an instance to specify Web API Routing.
Here is an instance of Web API routing –
Config.Routes.MapHttpRoute(
identify: "MyRoute,"//route identify
routeTemplate: "api/{controller}/{motion}/{id}",//as you may see "API" is initially.
defaults: new { id = RouteParameter.Optional }
);
67. How to register an exception filter globally?
You can use the next code to register an exception filter globally –
GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());
68. What are the completely different HTTP strategies utilized in Web API?
Though there are a number of HTTP verbs or strategies, an important and often used ones are GET, PUT, POST and DELETE.
GET – It is used to retrieve info of the useful resource at a specified URI.
PUT – The PUT methodology is used to replace the values of a useful resource at a specified URI.
POST –POST methodology is used to create a brand new request and ship information to the respective server.
DELETE –This methodology is used to take away the present useful resource at a specified URI.
The performance of those HTTP verbs will be summed up utilizing the acronym CRUD through which every letter corresponds to completely different motion –
C stands for Create or POST (creating information)
R stands for Read or GET (information retrieval)
U stands for Update or PUT (updating information)
D stands for Delete or DELETE (deleting information)
Other much less often used HTTP verbs or strategies as per the requirement embrace –
HEAD –This methodology works the identical manner because the GET methodology and is primarily used to switch the header part.
OPTIONS –This methodology helps determine and describe the communication possibility for a selected useful resource.
CONNECT –It is used to determine two-way communication between the server and the specified vacation spot with the assistance of a given URI.
TRACE – This methodology is used for diagnostic functions to invoke a loop-back message alongside the goal path and use that information for testing.
69. What is HttpConfiguration in Web API?
HttpConfiguration refers back to the world set of providers used to override the behaviour of the default Web API. It has the next properties –
- ParameterBindingGuidelines
- Formatters
- MessageHandlers
- DependencyResolver
- Services
70. Explain the code snippet to indicate how we will return 404 errors from HttpError.
Here’s the Code for returning 404 error from HttpError –
string message = string.Format(“TestCustomer id = {0} not found”, customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotDiscovered, message);
71. What is the code used to register an exception filter from the motion?
One can register an exception filter utilizing the next code –
[NotImplExceptionFilter]
public TestCust GetMyTestCust (int custno)
{
//write the code
}
72. What are the testing instruments or API for creating or testing internet API?
- CFX
- Axis
- Jersey API
- Restlet
73. How are you able to cross a number of advanced sorts in Web API?
Two methods to cross a number of advanced sorts in Web API embrace – Newtonsoft array and utilizing ArrayList.
74. What is the code for passing ArrayList in .NET Web API?
ArrayList paramList = new ArrayList();
Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};
Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p);
75. What is an HTTP standing code?
HTTP standing codes are three-digit integers issued by the server in response to the request made by the shopper, the place every quantity specifies a that means.
76. How are completely different HTTP Status Codes categorized?
All HTTP standing codes are categorized into 5 courses. These embrace –
- 1xx (Informational) – It signifies that the server has acquired a sure request and the method is continuous.
- 2xx (Successful)–It signifies that the request was profitable and accepted.
- 3xx (Redirection)–It signifies that the request has been redirected and its completion would require additional motion or steps.
- 4xx (Client Error)–It signifies that the request for the net web page can’t be reached as both it’s unavailable or has unhealthy syntax.
- 5xx (Server Error)–It signifies that the server was unable to finish a sure request regardless that the request appears legitimate.
77. What is the generally noticed HTTP response standing code?
There are many HTTP codes which might be seen and others that aren’t seen at first however will be noticed by the administrator utilizing browser extensions or sure instruments. Identifying and rectifying these errors is essential to reinforce the consumer expertise and optimize search engine rating over the net.
Here are probably the most generally seen HTTP standing codes at a look –
- Status code 200 – request is okay.
- Status code 201 – Created
- Status code 202 – Accepted
- Status code 204 – No content material
- Status code 301 – Moved completely
- Status code 400 – Bad request
- Status code 401 – Unauthorized
- Status code 403 – Forbidden
- Status code 404 – Not discovered
- Status code 500 – Internal server error
- Status code 502 – Bad gateway
- Status code 503 – Service Unavailable
78. How do web site homeowners keep away from HTTP standing codes?
To be certain that the web site is working easily and provides an optimum consumer expertise, the administrator or web site proprietor has to work persistently to maintain routinely generated error codes to the minimal and likewise to determine 404 errors.
The 404 HTTP standing code will be prevented by redirecting customers by a 301 code to another location reminiscent of the beginning web page. The bounce-back charge of web site guests can be decreased with the guide creation of error pages.
79. Name methodology that validates all controls on a web page?
Page.Validate() methodology system is executed to validate all controls on a web page.
80. What is the usage of DelegatingHandler?
DelegatingHandler is a course of used to develop a customized server-side HTTP message handler in ASI.Net Web API and chain message handlers collectively.
81. What do you imply by Internet Media Types?
Formerly often called the MIME sort, it refers to the usual design for figuring out content material on the web reminiscent of the kind of info a bit of information accommodates.
For instance, if we obtain a file over the e-mail as an attachment, this identifier will be helpful in realizing the media sort of the attachment info contained within the header in order that the browser can launch the suitable plug-in.
It is an effective apply to know info on media sorts as each web media sort has to adjust to the next format –
[type]/[tree.] (Optional)[subtype][+suffix](Optional)[;parameters]
Each media sort will need to have the ‘type’ and the ‘subtype’ that signifies the kind of info it accommodates. For occasion,
Image– sort/png- subtype
Application– sort/rss- subtype+xml
82. Can a Web API return an HTML View?
Web API can’t return an HTML view. If you need to return views, it’s best to make use of MVC.
83. What is the standing code for “Empty return type” in Web API?
The standing code 204 will return empty content material within the response payload physique.
84. Can you elaborate on completely different Web API filters?
Filters are used so as to add further logic earlier than or after particular phases of request processing throughout the Web API framework.
There are various kinds of filters. Some built-in ones deal with duties reminiscent of authorization, response caching, and so forth. whereas customized filters will be created to deal with issues like error dealing with, authorization, and so forth.
Filter run throughout the ASP.Net pipeline, additionally known as the filter pipeline and varied kinds of filter relying on the execution at a selected stage on this filter pipeline embrace –
- Authentication filter –It helps to authenticate consumer particulars and HTTP requests.
- Authorization filter –It runs earlier than controller motion to find out whether or not the consumer is allowed or not.
- Resource filter –It runs after authorization and runs code earlier than the remainder of the filter pipeline. For instance – OnResourceExecuted runs code after the remainder of the pipeline will get accomplished.
- Action filter –It is used so as to add further logic earlier than motion will get executed and has the power to vary the consequence returned from a selected motion.
- Exception filter –It is used when controller motion throws unhandled errors that happen earlier than the response physique is written.
- Override filter –it’s used to vary the motion strategies or different filters.
- Result filter –It runs code both earlier than or after the execution of motion outcomes.
85. What is the distinction between ApiController and Controller?
ApiController focuses on returning information organized in collection and despatched to the shopper.
public class TweetsController : ApiController
{
// GET: /Api/Tweets/
public List<Tweet> Get()
{
return Twitter.GetTweets();
}
}
Controller, however, gives regular views and handles HTTP requests.
public class TweetsController : Controller
{
// GET: /Tweets/ [HttpGet] public ActionResult Index()
{
return Json(Twitter.GetTweets(), JsonRequestHabits.AllowGet);
}
}
86. What is the distinction between XML and JSON?
XML is an acronym for eXtensible Markup Language and is designed to retailer and ship information. JSON is an acronym for JavaScript Object Notation and is used to retailer and switch information when information is distributed from a server to an internet web page.
Except for storing information in a selected format, XLM doesn’t do a lot whereas JSON is a light-weight and straightforward to grasp format for storing information, extensively utilized in JavaScript.
87. What do you imply by Caching?
Caching refers back to the strategy of storing information in momentary storage in a cache for future use. It retains copies of all often used information and recordsdata within the cache, which permits the web site to render sooner. It additionally helps enhance scalability in order that the info will be instantly retrieved from the reminiscence when wanted.
The easiest cache in ASP.Net Web API relies on IMemoryCache.
Some key benefits of Caching embrace –
- Minimizes database hits
- Helps internet pages render sooner
- Reduces community prices
- Faster execution of course of
- Highly environment friendly for each shopper and server
- Reduces load time on the server
- Best web page administration technique to enhance software’s efficiency
88. What are the kinds of Caching?
There are various kinds of caching in ASP.NET Web API. These are –
- Page output caching –This sort of caching shops the not too long ago used copy of the info within the reminiscence cache to enhance webpage efficiency. The cached output is fetched instantly from the cache and despatched to the appliance.
Here’s the code to implement web page output caching –
<%@ OutputCache Duration="30" RangeByParam="*" %>
- Page fragment caching –In this type of caching, solely fragments of information or internet pages are cached as a substitute of your entire web page. It is useful when the webpage accommodates dynamic and customary sections and the consumer needs to cache some parts of it.
- Data caching –In this type of caching, information is saved in momentary storage in order that it may be retrieved later. Here is the syntax to retailer information utilizing the Cache API –
Cache[“key”] = “value”;
Web API FAQs
An online API is an interface that lets you entry and manipulate information over the web. It is often used to entry information from an internet server, and can be utilized to create internet functions or web sites. It will be developed with the assistance of various applied sciences reminiscent of ASP.NET, or Java.
A programming interface sort that gives communication between software program functions. It is commonly used to offer the interface for shopper functions and web sites. It can be used to entry and save information from a database.
There are primarily 4 kinds of API used for web-applications. They are as follows:
– public,
– accomplice,
– personal, and
– composite.
The full type of API is Application Programming Interface and it might prolong the performance of an internet browser. An API would permit a 3rd social gathering reminiscent of Facebook to instantly entry the assorted features of an exterior software, reminiscent of ordering a product on Amazon.
These Web API interview questions cowl the essential floor of Web API and make it simpler for the scholars and professionals to make clear their fundamentals on this topic. For a few of the industry-leading on-line programs on Web API, you may head to Great Learning Academy and upskill on this area.
Also Read: Top 25 Common Interview Questions