Latest Asp.net Web API interview questions with answers for beginners. In this post we cover .net web api and .net core web api, so you may find different solution for same question (specified with version number).
to create an api in .net we just need to add an roter atrribute on top of controller class [Route("api/[controller]")]
namespace WebTrainingRoom { [Route("api/[controller]")] public class TestController : Controller { [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } } }
We should create HttpResponseMessage type post instead of void, then we can create a response object with exception object, we can write try catch block this way.
try { } catch (Exception ex) { var returnErrMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); return returnErrMessage; }
Well, we can fix the (Formatters) return type, we can remove any formatter (MediaTypeFormatter) from web API project just by adding few lines in “WebApiConfig.cs”
In following example suppose we want to return only JSON type,
So added config.Formatters.Remove(config.Formatters.XmlFormatter);
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); //Suppose we want to return only JSON type,then we can remove XML formatter this way. config.Formatters.Remove(config.Formatters.XmlFormatter); } }
Asp.net Web API is for building HTTP Services that can reach to different clients like browsers, mobile, IoT Devices, etc, but Web API is limited to HTTP based services, it can work only on HTTP protocol
On the other hand WCF (Windows Communication Foundation) is designed for building service oriented architecture (SOA), we can build service using WCF that supports multiple transport protocol like HTTP, TCP, MSMQ, etc.
We can return html content from web api action result just by adding attribute [Produces("text/html")]
,
Attribute indicate the result will be html content, can be a form, image, newsletter etc.
[HttpGet("{id}")] [Produces("text/html")] public ActionResult<string> Get(int id) { string _result = "<b>Return HTML content using Web API method </b>"; return _result; }
Above solution, need some additional work to make it work for.net core version.
In asp.net core, we need to create a string formatter class public class HtmlOutputFormatter : StringOutputFormatter
and then register the class in configureServices method in startup file.
We can create api just by adding an api controller attribute class like example below.
[ApiController] [Route("[controller]")] public class OrderController : ControllerBase { }
[Route("GetCustomNameExample")]
[Route("GetOrders")] [HttpGet] [ProducesResponseType(typeof(IEnumerable <Order>),(int)HttpStatusCode.OK)] public async Task <IActionResult> GetOrders() { var orders = await _queryService.GetNewOrdersAsync(); return Ok(orders); }
That we can have multiple get method in same api controller, below is the default get method of same controller
[Route("")] [HttpGet] public IEnumerable<OrderItem> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index =< new OrderItem { OrderDate = DateTime.Now.AddDays(index), ProductId = rng.Next(-20, 55), }) .ToArray(); }
Now, if consumer does not know the custom get method name, the above get method will serve the purpose.
First, let’s understand how that ProducesResponseType attribute was placed on top of the page actionresult
[Route("GetOrders")] [HttpGet] [ProducesResponseType(typeof(IEnumerable <Order>),(int)HttpStatusCode.OK)] public async Task <IActionResult> GetOrders() { var orders = await _queryService.GetNewOrdersAsync(); return Ok(orders); }
To answer the question, no, the ProducesResponseType attribute is not mandatory, without that also api inherently sent the status code, but this attribute works like a mediator, which provide additional information like the type of object we want to return along with status code.