Web Api
Web Api
ASP.Net Web API?
A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP based service.
Clients dealing with mobile applications and web browsers can consume Web API.
2. What are the differences between Web API and WCF REST
API?
A: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message
Queue, one-way messaging, and duplex communication. WEB API supports any media format,
even XML, JSON; while, WCF supports SOAP and XML format. ASP.Net Web API is ideal
for building HTTP services, while WCF is perfect for developing service-oriented applications.
To run Web API, there is no configuration required, while in the case of WCF, a lot of
configuration is required to run it.
A: It is the process that determines the action and controller that should be called.
A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin
restriction for JavaScript. Same-origin means a JavaScript only makes AAJAX call for web
pages within the same-origin.
You have to install the CORS nuget package by using Package Manager Console to enable
CORS in Web API.
Add EnableCors attribute to the Controller class and define the origin.
A: To secure an ASP.Net Web API, we need to control the Web API and decide who all can
access the API and who cannot access it. Web API can be accessed by anyone who knows about
the URL.
9. What are the differences between HTTP Get and HTTP Post?
Parameters of GET are included in the URL; while parameters of POST are
included in the body
GET requests do not make any changes to the server; while POST does make
changes to the server
A GET request is idempotent; while a POST request is non-idempotent
In a GET request, data is sent in plain text; binary and text data are sent
A: Web API can easily be used with ASP.Net Forms. You can add Web API Controller and
route in Application Start method in Global.asax file.
A: No, it is not possible as Web API creates an HTTP-based service. It is mostly available in
the MVC application.
Attribute Routing
External Authentication
CORS (Cross-Origin Resource Sharing)
OWIN (Open Web Interface for .NET) Self Hosting
IHttpActionResult
Web API Odata
[HttpGet]
public HttpResponseMessage Test()
///
return response;
}
[HttpPost]
public void Save([FromBody]string value)
How do we make sure that Web API returns data in JSON format
only?
A: To ensure that web API returns data in JSON format only, open “WebApiConfig.cs” file as
well as add the below line:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new
MediaTypeHeaderValue(“application/json”))
[ActionName(“InertUserData”)]
// POST api/
A: Handling errors or exceptions in Web API can be done with the help of the following classes
–
Using HttpResponseException –This exception class helps to return the HTTP
status code specified in the exception Constructor.
Using HttpError – This exception class helps to return meaningful error code
to the client as HttpResponseMessage.
Using Exception filters – Exception filters help in catching unhandled
exceptions or errors generated in Web API and they can be used whenever the
controller action method throws the unhandled error.
A: There are two ways how Web API application can be hosted:
Self Hosting
IIS Hosting
A: OData is the acronym for Open Data Protocol. It is a Rest-based data access protocol. OData
provides a way to manipulate data by making use of CRUD operation. ASP.Net Web API
supports OData V3 and V4.
To use OData in ASP.Net Web API, you would need an OData package. You have to run the
below command in the Package Manager Console.
Install-Package Microsoft.AspNet.Odata
A: CRUD operation can be performed by using entity framework with Web API.
A: ASP.Net Web API runs over HTTP protocol. You can create a class and get a class with
AuthorizationFilterAttribute. Now check if the requested URL has HTTPs.
A: Basic Authentication in ASP.Net Web API can be implemented where the client sends a
request with an Authorization header and word Basic. In Basic Authentication, the
Authorization header contains a word Basic followed by a base 64 encoded string.
What is ASP.Net identity?
What is REST?
A: REST stands for Representational State Transfer. This is an architectural pattern that helps in
exchanging data over a disseminated environment.
REST architectural pattern treats all the services as resources and a client can access these
resources by using HTTP protocol methods which include PUT, GET, POST, and DELETE.
A standard
A protocol
3.A replacement of SOAP
A: MVC is used to create web applications that can return views as well as data;
while ASP.NET Web API is used to create restful HTTP services simply, which returns only
data and no view. In MVC, the request is mapped to the actions name; while the request is
mapped to the actions based on HTTP verbs in Web API.
A: It is not true! It is rather just another way to build non-SOAP based services like plain XML
or JSON string. It comes with additional advantages such as using HTTP’s full features and
reaching more clients such as mobile devices, etc.
A: These are classes that are responsible for response data. The Web API understands the
request data format as well as sends data in the format as expected by the clients.
Which protocol is supported by Web API?
A: The only protocol supported by Web API is HTTP. Therefore, it can be consumed by a
client that supports HTTP protocol.
A: Both MVC and Web API are based on the principle of Separation of concerns and concepts
like controllers, routing, and models.
A: MVC is used for developing applications that come with User interfaces. The Views in MVC
are used to develop a User Interface. Web API is used for developing HTTP services. To fetch
data, the Web API methods are called by other applications.
A: Web API is consumed by a client that supports HTTP verbs such as DELETE, GET, PUT,
POST. They can quite easily be consumed by a client as Web API services do not need any
configuration. Web API can be consumed very easily by portable devices.
A: As Web API uses HTTP verbs, a client that can consume a Web API that needs ways to call
the Web API method. A client can use the HTTP verbs to call the action methods of the Web
API.
Take a look at the example given below. In order to call a method like GetEmployee, client can
use a jQuery method like:
1 $.get(“/api/Employees/1”, null, function(response) {
2 $(“#employees”).html(response);
3 });
Therefore, the method name above has no mention. As an alternative, GetEmployee method can
be called by using the GET HTTP verb.
1 [HttpGet]
3{
4 StudentRepository.Get(id);
5}
As the GetEmployee method can be seen decorated with the [HttpGet] attribute, different verbs
to map the different HTTP requests have to be used:
HttpGet
HttpPut
HttpPost
HttpDelete
2{
3 StudentRepository.Get(id);
4}
As it can start with GET, the above-mentioned method can be automatically mapped with the
GET request.
A: To add the certificate to the website, you can follow the steps mentioned below:
A: In order to enable SSL to ASP.NET web, you can click on project properties where you can
see this option.
A: // Restrict by Name
[Authorize(Users=”Shiva,Jai”)]
public class StudentController : ApiController
// Restrict by Role
[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController
[Route(“students/{id:int}”]
public User GetStudentById(int id) { … }
[Route(“students/{name}”]
public User GetStudentByName(string name) { … }
You can select the first route whenever the “id” segment of the URI is an integer. Or else, you
can choose the second route.
config.MapHttpAttributeRoutes();
Request body
URI
Custom Binding
routes.MapHttpRoute(
name: “myroute”,
routeTemplate: “api/{controller}/{id}”,
);
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
A: The default media types that are supported by Web API are XML, form-urlencoded data,
JSON, BSON. The other media types supported can be done by writing a media formatter.
A: The major disadvantage of “Other Return Types” in Web API is that error codes like 404
errors will not directly be returned.
What is the namespace for IHttpActionResult return type in Web
API?
A: System.Web.Http.Results namespace
We have several other technologies similar to Web API yet it is the most important and
preferred over others for several reasons –
Web API has the most lightweight architecture and provides an easy interface
for websites and client applications to access data.
It uses low bandwidth. This makes it ideal for even small bandwidth devices,
for instance, smartphones.
It can create non-SOAP-based HTTP services.
It can be consumed by a range of clients including web browsers, desktop and
mobile applications.
Web API is based on HTTP which makes it convenient to define, consume or
expose using REST-ful services.
It fits best with HTTP verbs for operations such as Create, Read, Delete or
Update.
Web API is more useful from the business point of view and finds its
applications in UI/UX to increase web traffic and interest in a company’s
services or products.
It can support a plethora of text and media formats such as JSON, XML, etc.
It can also support Open Data (OData) protocol.
It is most suitable for the MVC pattern which makes it ideal for experienced
developers in that pattern.
It can be easily built using technologies such as ASP.NET, JAVA, etc.
It is considered the best to create resource-oriented services.
In today’s hyper-connected digital world, we are moving web-based services towards mobile
applications. That means we need an API that is lightweight, secure, safe and compatible with
these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements
for building HTTP services consumed by a vast array of clients including browsers and modern
devices such as mobile phones, tablets, etc.
TestAPi in Web API refers to a utility library that allows developers to create testing tools as
well as automate tests for a .NET application.
How can we handle an error using HttpError in Web API?
The HttpError method is used in Web API to throw the response body’s error information. One
can also use the “CreateErrorResponse” method along with this one.
Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any
other application.
Basic Authentication in ASP.Net Web API is one where the client will send a request using the
word Basic with an Authorization header, followed by a base 64 encoded string.
Parameters are used in Web API to determine the type of action you take on a particular
resource. Each parameter consists of a name, value type and description that has the ability to
influence the endpoint response.
You can use the query API to get information about various entities within a data source.
The Get Method employs multiple primitive parameters. For instance, the Get method needs id
parameter to get product details –
You can use the following code to register an exception filter globally –
GlobalConfiguration.Configuration.Filters.Add (new
MyTestCustomerStore.NotImplExceptionFilterAttribute());
Though there are a variety of HTTP verbs or methods, the most important and frequently used
ones are GET, PUT, POST and DELETE.
PUT – The PUT method is used to update the values of a resource at a specified URI.
POST –POST method is used to create a new request and send data to the respective server.
DELETE –This method is used to remove the current resource at a specified URI.
The functionality of these HTTP verbs can be summed up using the acronym CRUD in which
each letter corresponds to different action –
Other less frequently used HTTP verbs or methods as per the requirement include –
HEAD –This method works the same way as the GET method and is primarily used to transfer
the header section.
OPTIONS –This method helps identify and describe the communication option for a specific
resource.
CONNECT –It is used to establish two-way communication between the server and the desired
destination with the help of a given URI.
TRACE – This method is used for diagnostic purposes to invoke a loop-back message along the
target path and use that data for testing.
HttpConfiguration refers to the global set of services used to override the behaviour of the
default Web API. It has the following properties –
ParameterBindingRules
Formatters
MessageHandlers
DependencyResolver
Services
Explain the code snippet to show how we can return 404 errors
from HttpError.
What are the testing tools or API for developing or testing web
API?
CFX
Axis
Jersey API
Restlet
Two ways to pass multiple complex types in Web API include – Newtonsoft array and using
ArrayList.
All HTTP status codes are categorized into five classes. These include –
1xx (Informational) – It indicates that the server has received a certain request
and the process is continuing.
2xx (Successful)–It indicates that the request was successful and accepted.
3xx (Redirection)–It indicates that the request has been redirected and its
completion will require further action or steps.
4xx (Client Error)–It indicates that the request for the web page cannot be
reached as either it is unavailable or has bad syntax.
5xx (Server Error)–It indicates that the server was unable to complete a
certain request even though the request seems valid.
There are many HTTP codes that are visible and others that are not visible at first but can be
observed by the administrator using browser extensions or certain tools. Identifying and
rectifying these errors is crucial to enhance the user experience and optimize search engine
ranking over the web.
Here are the most commonly seen HTTP status codes at a glance –
To ensure that the website is running smoothly and offers an optimal user experience, the
administrator or website owner has to work consistently to keep automatically generated error
codes to the minimum and also to identify 404 errors.
The 404 HTTP status code can be avoided by redirecting users by a 301 code to the alternative
location such as the start page. The bounce-back rate of website visitors can also be decreased
with the manual creation of error pages.
Formerly known as the MIME type, it refers to the standard design for identifying content on
the internet such as the type of information a piece of data contains.
For example, if we receive a file over the email as an attachment, this identifier can be useful in
knowing the media type of the attachment information contained in the header so that the
browser can launch the appropriate plug-in.
It is a good practice to know information on media types as every internet media type has to
comply with the following format –
[type]/[tree.] (Optional)[subtype][+suffix](Optional)[;parameters]
Each media type must have the ‘type’ and the ‘subtype’ that indicates the type of information it
contains. For instance,
Web API cannot return an HTML view. If you want to return views, it is best to use MVC.
What is the status code for “Empty return type” in Web API?
The status code 204 will return empty content in the response payload body.
Filters are used to add extra logic before or after specific stages of request processing within the
Web API framework.
There are different types of filters. Some built-in ones handle tasks such as authorization,
response caching, etc. while custom filters can be created to handle concerns like error
handling, authorization, etc.
Filter run within the ASP.Net pipeline, also referred to as the filter pipeline and various types of
filter depending on the execution at a particular stage in this filter pipeline include –
Authentication filter –It helps to authenticate user details and HTTP requests.
Authorization filter –It runs before controller action to determine whether the
user is authorized or not.
Resource filter –It runs after authorization and runs code before the rest of the
filter pipeline. For example – OnResourceExecuted runs code after the rest of
the pipeline gets completed.
Action filter –It is used to add extra logic before action gets executed and has
the ability to change the result returned from a particular action.
Exception filter –It is used when controller action throws unhandled errors
that occur before the response body is written.
Override filter –it is used to change the action methods or other filters.
Result filter –It runs code either before or after the execution of action
results.
ApiController specializes in returning data arranged in series and sent to the client.
Controller, on the other hand, provides normal views and handles HTTP requests.
public class TweetsController : Controller { // GET: /Tweets/ [HttpGet] public Act
1JsonRequestBehavior.AllowGet); } }
XML is an acronym for eXtensible Markup Language and is designed to store and send data.
JSON is an acronym for JavaScript Object Notation and is used to store and transfer data when
data is sent from a server to a web page.
Except for storing data in a specific format, XLM does not do much whereas JSON is a
lightweight and easy to understand format for storing data, widely used in JavaScript.
Caching refers to the technique of storing data in temporary storage in cache for future use. It
keeps copies of all frequently used data as well as files in the cache which enables the website
to render faster. It also helps improve scalability so that the data can be directly retrieved from
the memory when it is needed in the future.
Page output caching –This type of caching stores the recently used copy of
the data in the memory cache to improve webpage performance. The cached
output is fetched directly from the cache and sent to the application.
Page fragment caching –In this form of caching, only fragments of data or
web pages are cached instead of the entire page. It is helpful when the
webpage contains dynamic and common sections and the user wants to cache
some portions of it.
Data caching –In this form of caching, data is stored in temporary storage so
that it can be retrieved later. Here is the syntax to store data using the Cache
API –
Cache[“key”] = “value”;