Quick Interview Questions on Asp.net Web API:


Top 12 WebAPI Interview Questions and Answers in 2023 - USMTECHWORLD.

1. What is Asp.Net WebAPI?

Answer:
Asp.net webapi is a framework that helps to build http services on top of browsers,mobile devices,IOT devices,etc.It can also be used to build REST application on .Net framework.

2. What are the advantages of Asp.Net WebAPI?

Answer:
a)It has feature called Content Negotiation. b)It has feature called OData. c)It has routing features like Asp.net MVC d)Self hosting feature is available.(i.e it can be hosted in IIS as well as it can be hosted outside IIS) e)It supports model binding and validations

3. What is REST?

Answer:
REST means Representational State Transfer.It has following constraints. a)Stateless: The main feature of REST is that the service is stateless.The client request should contain the necessary information and will be sent to server.The server need not remember whatever details sent by the client. This concept is called Stateless nature. The server response can be cached by clients. b)It allows our response is cached or not and hence it improves the performance. c)it fully supports JSON AND XML

4. Why Model becomes null ,when you pass model from Angular to WebAPI?

Answer:
The following may be the reason for model becoming null in WebAPI:

5. What are the WebMethods in Asp.Net WebAPI?

Answer:
WebMethods are also called HTTP Methods.The HTTP Methods are the one ,which retrieve data from the server,submit data to the server and delete data from the server.When client request the server ,the request is carried out through this HTTP Methods such as GET,POST,PUT AND DELETE. The following are the most common HTTP Methods used in WebAPI.

The above one corresponds to CRUD operations in WebAPI.

GET: The GET method is used to fetch data from the server at the specified resource.for eg:-you have an API endpoint say /customers.Making get request to customers endpoint will return all customers. The GET request is safe and Idempotent(when you call same function with same value and the result is same)

POST: The POST methods is used to send data to the SERVER to create or update a resource.The data sent to the server is stored in "Request Body" of the HTTP Request.The basic example is registeration form,the user will fill all the details in registration form,the data will be put inside the response body of the request and sent to server.The input format may be JSON,XML or other formats. The POST request is NON-IDEMPOTENT.It changes data on the server by creating or updating the resource.

PUT: The PUT request send data to the SERVER to Update or Create a Resource.The PUT request is IDEMPOTENT.That means calling PUT request multiple times will produce the same result. When PUT request is created the server sends the response with (201)Created.However if the request modifies the resource,the server will return (200)OK or(204)No Content.

PATCH: The PATCH request will do partial modification to the resource.The PATCH request is NON-IDEMPOTENT. In simple words,when the client needs to update only single field of the resource.We can use PATCH method.So it is unnecessary to pass entire entity

DELETE: The DELETE request will delete the resource at the specified URL.For example,if we want to remove particular user from the resource,we need to pass userid to users endpoint.

6. How will you call WebAPI from WebMethod,is it Possible?

Answer:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:61258/api/values/20");
request.Method = "GET";
request.Headers["Authorization"] = "Token";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Note: Web method is Soap service and Web Api is rest service.

7. Whether can we perform more than one webmethod on particular action in webapi

Answer:
Yes,by using [AcceptVerbs]

[AcceptVerbs("POST", "PUT")]
public IHttpActionResult AddProduct(string productname)
{

return Ok();
}
Note: Web method is Soap service and Web Api is rest service.

8. What are the various return types in WebAPI?

Answer:
The various return types of WebAPI action methods are as follows:-

Void: This action method will not return anything.The action method with void return type will return 204 No Content response.

PRIMITIVE OR COMPLEXTYPE This action method will return data type like int,string or complex type like List.

 public class SimpleController : ApiController{
      public List Get([FromBody] Customer cust){
         return new List{
            $"The Id of the Customer is {cust.Id}",
            $"The Name of the Customer is {cust.Name}"
         };
      }
   }
The action method with void return type will return 200.

HTTPRESPONSEMESSAGE This action method will return data type as HTTPRESPONSEMESSAGE.When we want to customize the return type of an Action method then we will use this HTTPRESPONSEMESSAGE return type.Here the responses are customized by providing status code,content type and data to be returned to HttpResponseMessage.

public class SimpleController : ApiController{
public HttpResponseMessage Get([FromBody] Customer cust){
if(cust.Id > 0){
return Request.CreateResponse(HttpStatusCode.OK, $"The Customer Id is {cust.Id} and customer Name is {cust.Name}");
} else {
return Request.CreateResponse(HttpStatusCode.BadRequest, $"InValid Customer Id");
}
}
}
Since invalid customer id is passed to the function,it returns 400 bad request with customized message.

IHTTPACTIONRESULT: This IHTTPActionResult was introduced in WebAPI 2.0.The IHTTPActionResult is an interface containing ExecuteAsync method,which asynchronously creates an HttpResponseMessage instance.

public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationtoken);
}
If a controller actions returns an IHttpActionResult, WebAPI calls ExecuteAsync method to create HttpResponseMessage. This is simple example of IHttpActionResult that returns string response.
public class CommonResult:IHttpActionResult
{
 string _value;
 HttpRequestMessage _request;
 public CommonResult(string value,HttpRequestMessage message)
{
_value=value;
_request=request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationtoken)
{
          var response= new HttpResponseMessage()
            {
                Content=new StringContent(_Value),
                RequestMessage=_request
            }  ;
            return Task.FromResult(response);
}
 
}
            
Lets implement the above CommonResult in controller.
public class TestController:ApiController
{
public IHttpActionResult Get()
{
return new CommonResult("hello USMTECHWORLD",Request);
}
}

9. What is the default return format of WebAPI?

By default WebAPI returns in XML Format.But sometimes client needs to return in JSON format also. To return format in JSON, need to add code in WebAPIConfig.cs.The user will send query parameter in url , whether he needs in json or xml.
http://localhost:8525/api/Users?type=json

  public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(name:"Defaultext",
                            routeTemplate:"api/{controller}/{id}",
                            defaults:new {id=routeparamter.optional});

//Add formatter for JSON
config.Formatters.JsonFormatter.MediaTypeMappings.Add(
                        new QueryStringMapping("type","json",new MediaTypeHeaderValue("application/json")));
//Add formatter for xml
config.Formatters.XMLFormatter.MediaTypeMappings.Add(
                        new QueryStringMapping("type","json",new MediaTypeHeaderValue("application/xml")));

}

10. What is the difference between WebService and WebAPI?

11. How will you handle Exceptions in WebAPI?

HTTPRESPONSEEXCEPTION:
This exception class allows us to return Httpresponsemessage to the client.It returns Httpstatuscode.
public Customer Get([FromODataUri] int custid)
{
Employee data = context.Employees.Where(k => k.Id == custid).FirstOrDefault();
if (data == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return data;
}
        

HTTPERROR:-
The CreateErrorResponse method of Request returns meaningful error code and message to the client.It creates an instance of HTTPERROR object and returns it as HTTPRESPONSEMESSAGE object.
public httpresponsemessage get(int id)
{
customer custobj=context.customers.where(x=>x.id==id).Firstordefault();
if(custobj==null)
{
            string message = string.Format("No customer found with ID = {0}", id);
return request.createerrorresponse(httpstatuscode.notfound,message)
}

}

Using Exception Filters:-
The exception filters are used to handle Unhadled Exceptions in WebAPI.This filter is executed when an action method throws Unhandled exception i.e other than Http response exception.We can decorate both action method and controller.Let us see to implement this custom exception filter.
using web.http.filters;
using system.net.http;
Public class CustomExceptionFilter:ExceptionFilterAttribute
{
public override void onException(HttpActionExecutedContext actioncontext)
{
string exceptionmessage;
if(actioncontext ==null)
{
exceptionmessage = actioncontext.Exception.Message;
}
else
{
            exceptionmessage = actioncontext.Exception.InnerException.Message;
}
actioncontext.response=exceptionmessage;
//or we can log it as custom message
             var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = newStringContent(“An unhandled exception was thrown by service.”),
                    ReasonPhrase = "Internal Server Error.Please Contact your Administrator."
            };
            actionExecutedContext.Response = response;

}

}

We can register the custom exception filter by following ways:-
- Decorate action with exception filter
- Decorate controller with exception filter
- Reguster Globally
to apply custom filter to specific action.
[CustomExceptionFilter]
public HttpResponseMessage Get(int custid)
{
  
}
to apply custom filter to specific controller.
[CustomExceptionFilter]
public class EmployeeController : ApiController{
  
}
to apply custom filter globally.
public static class WebApiConfig
{
public static void Register(HttpConfigurationconfig)
{
config.Filters.Add(new CustomExceptionFilter());
}
}
EXCEPTION HANDLERS :
Suppose if the error is raised outside the action i.e in the following areas.
- Error inside the exception filter.
- Exception related to routing.
- Error inside the Message Handlers class.
- Error in Controller Constructor.
WebAPI 2 has new way to achieve this through global exception handling.Webapi provides ExceptionHandler" abstract class to handler. Let us see, how to implement this exceptionhandler.
public class GlobalExceptionHandler:ExceptionHandler
{
public async override TaskHandlerAsync(ExceptionHandlerContext context,CancellationToken cancellationtoken)
{
// Access Exception using context.Exception;
const string errorMessage = "An unexpected error occured";
var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError,
    new
    {
        Message = errorMessage
    });
response.Headers.Add("X-Error", errorMessage);
context.Result = new ResponseMessageResult(response);
}
}
}

Register this exceptionhandler in webapiconfig file
public static class WebApiConfig
{
public static void Register(HttpConfigurationconfig)
{
config.Filters.Add(new CustomExceptionFilter());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}
}

12. What is Content Negotiation in WebAPI?

Content negotiation works based on incoming HTTP requests and return response in various formats. The content negotiation is to select the prefered media type. It is based on media tuype and mediatypeformatter. Here client can decide in which format they want the response- xml,json etc. you can pass the format through accept header. for eg:- the client can specify the format for the reqponse in accept header like the following. AccepL:application/xml returns xml Accept:application/json return json

13. Why do we have to specify FromBody and FromUri in WebAPI?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding. SimpleType:If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. We can use [FromUri] attribute to access value from Simple type such as int,bool,double etc. complex types: For complex types, Web API tries to read the value from the message body, using a media-type formatter. We can use [FromBody] attribute to access from request body.

public HttpResponseMessage Put([FromBody]int id, [FromUri]Customer cust)
{
try
{
using (CustomerDBEntities entities = new CustomerDBEntities())
{
var entity = entities.Customer.FirstOrDefault(e => e.ID == id);
if (entity == null)
{
    return Request.CreateErrorResponse(HttpStatusCode.NotFound,
        "Customer with Id " + id.ToString() + " not found to update");
}
else
{
    entity.FirstName = employee.FirstName;
    entity.LastName = employee.LastName;
             
    entities.SaveChanges();
    return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
We can change this default parameter binding process by using [FromBody] and [FromUri] attributes.