Web API Interview Questions and Answers Part 2

1. What are the return types supported in Web API?
Ans. 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.

5. How do you construct HtmlResponseMessage?
Ans. Following is the way to construct to do so,

public class TestController : ApiController
{
    public HttpResponseMessage Get()
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("Testing", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    } 
}

6. What is the status code for "Emptry return type" in Web API?
Ans. void returns empty content and its code is 204.

7. What is the difference between Web API and MVC routing?
Ans.  Web API uses the HTTP method but not the URI path to select the action. 

8. Is it possible to have MVC kind of routing in Web API?
Ans. Yes, we can implement MVC kind of routing in Web API.

9. Where is the route is defined in Web API?
Ans. Route is defined in the WebApiConfig.cs file, which is placed in the App_Start directory.

App_Start -->  WebApiConfig.cs

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

10. Why "api/" segment is used in Web API routing?
Ans. It is used to avoid collisions with ASP.NET MVC routing.


 






Subscribe

Receive Quality Tutorials Straight in your Inbox by submitting your Email below:

Delivered by FeedBurner

Protected by Copyscape Duplicate Content Checker