Labels

Saturday, July 6, 2019

MS - ASP.NET WebAPI

Here we'll talk about ASP.NET WebAPI, can be build either thru .NET Framework or .NET Core

Project Structure:









































More Details:

1) What is Web API? 
WebAPI is a framework which helps you to build/develop HTTP services.
WebAPI support HTTP protocol
Web API is supported by NET 4.0 version
Web API uses JSON.NET library for JSON serialization.

2) Why is Web API required? Is it possible to use RESTful services using WCF?
  Yes, we can still develop RESTful services with WCF. However, there are two main reasons that prompt users to use Web API instead of RESTful services.
- Web API increases TDD (Test Data Driven) approach in the development of RESTful services.
- If we want to develop RESTful services in WCF, you surely need a lot of config settings, URI templates, contracts & endpoints for developing RESTful services using web API.

3) What is the benefit of using REST in Web API?
- REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps.
- Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication

4) What is SOAP?
- SOAP is an XML message format used in web service interactions.
- It allows to send messages over HTTP or JMS, but other transport protocols can be used.
- It is also an XML-based messaging protocol for exchanging information among computers.

4) What is the benefit of WebAPI over WCF?
 - WCF is designed to exchange standard SOAP-based messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ, etc.
- On the other hand, ASP.NET Web API is a framework for building non-SOAP based services over HTTP only.
- WCF services use  SOAP protocol while HTTP never use SOAP protocol. This makes WebAPI lightweight since SOAP (XML Based) is not used.
- Being Non-XML ,reduces the data which is transferred to resume service.
- Moreover, WEBAPI never needs too much configuration like WCF.
- Therefore, the client can interact with the service by using the HTTP verbs.

4) Differences between MVC and WebAPI
- MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.
- WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.

4) What are the advantages of Web API?
- Support for OData
- Filters
- Content Negotiation
- Self-Hosting & IIS Hosting
- Routing
 - Model Bindings & Validation
-  Response generated in JSON or XML format using MediaTypeFormatter

4) Some New Features In ASP.NET Web API 2.0:
- Attribute Routing
- External Authentication
- CORS (Cross-Origin Resource Sharing)
- OWIN (Open Web Interface for .NET) Self Hosting
- IHttpActionResult
- Web API OData

4) What are main return types supported in Web API? 
- Void – It will return empty content
- HttpResponseMessage – It will convert the response to an HTTP message.
- IHttpActionResult – internally calls ExecuteAsync to create an HttpResponseMessage
- Other types – You can write the serialized return value into the response body

- Notes:
{
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;
}


5) Web API supports which protocol? HTTP

6) Which .NET framework supports Web API? - NET 4.0 and above version supports web API.

7) Web API uses which of the following open-source library for JSON serialization? - JSON.NET library for JSON serialization.

8) How Can assign alias name for ASP.NET Web API Action? 
- We can give alias name for Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

[HttpPost]
[ActionName("SaveStudentInfo")]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

[HttpPost]
[ActionName("SaveStudentInfo")]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

9) How you can return View from ASP.NET Web API method?
- No, we can’t return a view from ASP.NET Web API Method.
- Web API creates HTTP services that render raw data. However, it’s also possible in ASP.NET MVC application.


10). How to register routes in WebAPI ?

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }


11). How to register Global Filters"

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}

12) What New Features comes with ASP.NET Web API 2.0?
- Attribute Routing
- Cross-Origin Resource Sharing
- External Authentication
- Open Web Interface NET
- HttpActionResult
- Web API OData

13) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
- 500 – Internal Server Error
 - E.g.
[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
if(id > 100)
{
throw new ArgumentOutOfRangeException();
}
return Ok(id);
}





















14) What is the difference between ApiController and Controller?
- Use Controller to render your normal views.
- ApiController action only return data that is serialized and sent to the client.




























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

- But it’s really hard to support certain URI patterns using conventional routing approach like nested routes on 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:

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


Quick Links:



Hope this helps.

Arun Manglick

No comments:

Post a Comment