Tuesday, November 17, 2020

ASP.NET Web API Interview questions

 


1.What is Web API? 

ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of the .NET Framework. Using ASP.NET Web API we can create non-SOAP based services like plain XML or JSON strings etc. with many other advantages 

Create resource-oriented services using the full features of HTTP




2.What is Representational state transfer or REST?

REST is an architectural style, which has defined guidelines for creating services that 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 –
        Routes.MapHttpRoute(
            Name: "MyFirstWebAPIRoute",
            routeTemplate: “api/{controller}/{id}
            defaults: new { id = RouteParameter.Optional
            }
            };


4.What are the advantages of Web API?

Using ASP.NET Web API has a number of advantages, but the core of the advantages are: 

  • It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE etc for all CRUD operations.
  • Complete support for routing.
  • Response generated in JSON or XML format using MediaTypeFormatter.
  • It has the ability to be hosted in IIS as well as self-host outside of IIS.
  • Supports Model binding and Validation.
  • Support for OData.


5.How to Return View from asp.net WebAPI Method?

No, we can't return view from ASP.NET Web API method.Web API creates HTTP services that render raw data.

6.Can we use web API with asp.net Webform?

Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be used with ASP.NET Web Form.
It can be done in three simple steps as follows: Create a Web API Controller
Add a routing table to Application_Start method of Global.asax
Make a jQuery AJAX Call to Web API method and get data 


7.What are Exception Filters?

Exception filters will be executed when some of the exceptions are unhandled and thrown from a controller method. The reason for the exception may be anything. Exception filters will implement the "IExceptionFilter" interface. 

8.What is Attribute Routing in Asp.net Web API 2.0?

ASP.NET Web API v2 now support “Attribute Routing” along with convention-based approach. In convention-based routes, the route templates are already defined as follows:
        Config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{Controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );
So, any incoming request is matched against an already defined route template and further routed to matched controller action. But it’s really hard to support certain URI patterns using conventional routing approaches like nested routes on the same controller.

For example, authors have books or customers have orders, students have courses etc.
Such patterns can be defined using attribute routing i.e. adding an attribute to controller action as follows:

=> books/1/authors

[Route("books/{bookId}/authors")]
public IEnumerable GetAuthorsByBook(int bookId) { ..... }


=> customers/1/orders

[Route("customers/{customerId}/orders")]
public IEnumerable GetOrdersByCustomer(int customerId) { ..... }


=> students/1/courses  

[Route("students/{studentId}/courses")]
public IEnumerable GetCoursesByStudent(int studentId) { ..... }



9.Explain CORS(Cross-Origin Resource Sharing)?




ASP.NET WebAPI is a trending technology in today’s world. Everyone tries to access the service through AJAX requests on the server-side. The problem is when a WebAPI is hosted and the other applications on different domains try to access the WebAPI through a request.

Here, enabling CORS plays a vital role in WebAPI.CORS (Cross-origin resource sharing) is a technique that allows restricted resources on a web page to be requested from another domain outside the domain of which the first resource was served.

A web page may freely attach cross-origin images, scripts, stylesheets, iframes, and videos. The same-origin security policy by default does not allow certain “cross-domain” requests, notably Ajax requests. 

10.WCF RESTful service Vs ASP.NET Web API?

WCF REST: Microsoft introduced “WebHttpBinding” to be used for creating WCF RESTful Services. HTTP Methods are mapped to attributes, for example, “WebGet” for GET method and “WebInvoke” for the POST.

ASP.NET Web API: As compared with WCF REST, Web API supports full features of HTTP. It's possible to host Web API in IIS as well as in an application.







SOAP

HTTP

It supports web socket or WS-Addressing, WS-Security and SOAP headers.

HTTP Message flows never use web socket or WS-Addressing, WS-Security, SwA, or MTOM.

A common SOAP has a logical tree format which is independent of the bitstream format.

HTTP is something that uses different standards, such as REST or XML-RPC.

Runtime checking against WSDL is permitted in SOAP.

Not available in HTTP.

Automatic processing of SOAP with Attachments (SwA) is possible here.

In HTTP message flows that interact with Web services only.

Automatic processing of Message Transmission Optimization Mechanism (MTOM) is also feasible.

HTTP nodes can process SwA messages also, but it must use the MIME message domain and design flow should be done to handle the attachments explicitly. Custom logic to extract and parse the SOAP should be written.

SOAP is a protocol to exchange XML-based messages and SOAP should use HTTP to transport those messages as already explained in the introduction section.

On the other hand, HTTP is a communications protocol which transports messages over a network, not like SOAP.

11.Write a code snippet for passing ArrayList in Web API?

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


12.How we can handle errors in Web API?

Below is the list of classes which can be used for error handling -
  • HttpResponseException
  • Exception Filters
  • Registering Exception Filters
  • HttpError

Explain how we can handle errors from "HttpResponseException"?

This returns the HTTP status code that 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;
}


13.How to register Web API exception filters?

Below are the options to register Web API exception filters –
  • From Action
  • From Controller
  • Global registration

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

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

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



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

Below is the code snippet for registering exception filters globally –

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


16.Explain Asp.net Identity?

This is the new membership system for asp.net. This allow 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

17.Why to use "FromUri" in Web API?

The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.

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




18.Why to use "FromBody" in Web API?

 The [FromBody] attribute is used to specify that the value should be read from the body of the request.

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) 
        //Code Here... 
}


19.What Is the Advantages of Token Based Authentication?

Token-based authentication is more secure.
They're specific to the user, the particular log-in session, and the security algorithm that the system uses. In other words, the server can identify when a token's been tampered with at any step and can block access.

A token is a piece of data which is created by a server, and which contains enough data to identify a particular user. The process starts by allowing users to enter their username and password which accessing a service. Once the user provides the username/password, a token is issued which allows users to fetch a specific resource - without using their username and password every time. 

This token is sent to the server with each request made by the client and contains all necessary information to validate a user’s request. The following diagram explains how Token-Based authentication is used in communication between clients and server.

Advantages of Token Based Authentication

The client application is not dependent on a specific authentication mechanism. The token is generated by the server and the Web API have some APIs to understand, validate the token and perform the authentication. This approach provides Loose Coupling between client and the Web API.

Maintaining cookies in native mobile applications is not an easy task. Using token based authentication, we can now provide support for mobile applications with much ease.


20.What is Asp.net Web API OData?

The Open Data Protocol (OData) is a data access protocol for the webOData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete). ASP.NET Web API supports both v3 and v4 of the protocol.

OData (Open Data Protocol) is an OASIS standard that defines the best practice for building and consuming RESTful APIs. ... OData RESTful APIs are easy to consume. The OData metadata, a machine-readable description of the data model of the APIs, enables the creation of powerful generic client proxies and tools.


21.Difference between WCF and Web API?

WCF:
  • WCF is a framework used for buil/develop service oriented applications. 
  • WCF can be consumed by clients which can understand XML. 
  • WCF supports wide range of protocols like HTTP, TCP, Named Pipes and more.
  • For each method there has to be attributes like – “WebGet” and “WebInvoke”
  • For REST service we need to use attribute “WebInvoke”.

Web API:
  • Web API is a framework used to build/develop HTTP based services.
  • Web API is an open source platform.
  • It supports only HTTP protocol.
  • Web API can be hosted in IIS or in application.
  • His returns XML or JSON to client. 

22.Write a code snippet for passing arraylist in web API?

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

23.What are the return types supported in Web API?

A Web API controller action can return any of the following:

1. Void - this type returns empty content (Status Code :204)
2. HttpResponseMessage - this will convert response to an HTTP response message.
3. IHttpActionResult ;- internally calls ExecuteAsync to create an HttpResponseMessage.
4. Some other type - we can write the serialized return value into the response body.

2. What is the namespace for IHttpActionResult return type in Web API?
Ans. System.Web.Http.Results namespace

3. What is the disadvantage of Other Return Types in Web API?
Ans. The main disadvantage of this approach is that you cannot directly return an error code like 404 error.

4. What are the default media types supported by Web API?
Ans. Web API supports XML, JSON, form-urlencoded data, BSON and also supports additional media types by writing a media formatter.

24.What is the status code for "Empty return type" in web API?

Void returns empty content and its code 204.

25.Is it possible to have MVC kind of routing in Web API?

Yes, We can implement MVC kind of routing in Web API.

26.Why "api/" segment is used in Web API routing?

To Avoid collisions with ASP.NET MVC routing.

27.What is RouteDictionary?

After route match, the placeholders are stored in dictionary object with keys as placeholders names
without curly braces and values are taken from URI path or from the defaults.Generally this dictionary is stored in IHttpRouteData object. 



28.Is {action} placeholders is mandatory or not in WebApi?

No,It is not mandatory. It is usually omitted in Webapi.


29.Does the default values need to be included from route Template path?

Defaults can also include a value that does not contain anywhere in the route template and
if the route matches that value is stored in the dictionary.

Example:

routes.MapHttpRoute(
    name: "sampleapi",
    routeTemplate: "api/sampleapi/{id}",
    defaults: new { controller = "testapi", id = RouteParameter.Optional }
); 



No comments:

Post a Comment

NET Core Code Security, Authorization/Authentication, and code architecture

Complex NET Core interview questions (Code Security, Authorization/Authentication, and code architecture)  _________________________________...