What is Web API?
Before we understand what is Web API, let’s see what is an API (Application Programing Interface).
As per Wikipedia’s Definition of API: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications.
To put it in simple terms, API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.
Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol. It is a concept and not a technology. We can build Web API using different technologies such as Java, .NET etc. For example, Twitter’s REST APIs provide programmatic access to read and write data using which we can integrate twitter’s capabilities into our own application.
ASP.NET Web API
The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view. It is like a webservice or WCF service but the exception is that it only supports HTTP protocol.
ASP.NET Web API Characteristics
- ASP.NET Web API is an ideal platform for building RESTful services.
- ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline
- ASP.NET Web API maps HTTP verbs to method names.
- ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.
- ASP.NET Web API can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
- ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.
ASP.NET Web API Versions
Web API Version | Supported .NET Framework | Coincides with | Supported in |
Web API 1.0 | .NET Framework 4.0 | ASP.NET MVC 4 | VS 2010 |
Web API 2 – Current | .NET Framework 4.5 | ASP.NET MVC 5 | VS 2012, 2013 |
ASP.NET Web API vs WCF
Web API | WCF |
Open source and ships with .NET framework. | Ships with .NET framework |
Supports only HTTP protocol. | Supports HTTP, TCP, UDP and custom transport protocol. |
Maps http verbs to methods | Uses attributes based programming model. |
Uses routing and controller concept similar to ASP.NET MVC. | Uses Service, Operation and Data contracts. |
Does not support Reliable Messaging and transaction. | Supports Reliable Messaging and Transactions. |
Web API can be configured using HttpConfiguration class but not in web.config. | Uses web.config and attributes to configure a service. |
Ideal for building RESTful services. | Supports RESTful services but with limitations. |
When to choose WCF?
- Choose WCF if you use .NET Framework 3.5. Web API does not support .NET 3.5 or below.
- Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named pipe.
- Choose WCF if you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security.
- Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange patterns.
When to choose ASP.NET Web API?
- Choose Web API if you are using .NET framework 4.0 or above.
- Choose Web API if you want to build a service that supports only HTTP protocol.
- Choose Web API to build RESTful HTTP based services.
- Choose Web API if you are familiar with ASP.NET MVC.
Web API Controllers
We created Web API with MVC project in the previous section where it generated a simple controller. Here, you will learn about Web API Controller in detail.
Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.
Web API controller is a class which can be created under the Controllers folder or any other folder under your project’s root folder. The name of a controller class must end with “Controller” and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.
The following is a simple controller class added by visual studio by default when we created a new Web API project in the Create Web API Project section.
Example: Simple Web API Controller
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MyWebAPI.Controllers
{
public class ValuesController : ApiController
{
// GET: api/values
public IEnumerable<string> Get()
{
return new string[] { “value1”, “value2” };
}
// GET: api/values/5
public string Get(int id)
{
return “value”;
}
// POST: api/values
public void Post([FromBody]string value)
{
}
// PUT: api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/values/5
public void Delete(int id)
{
}
}
}
As you can see in the above example, ValuesController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.
Based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), Web API decides which Web API controller and action method to execute e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API.
The following figure illustrates the significance of Web API controller and action methods.
If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.
Example: Simple Web API Controller
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MyWebAPI.Controllers
{
public class ValuesController : ApiController
{
[HttpGet]
public IEnumerable<string> Values()
{
return new string[] { “value1”, “value2” };
}
[HttpGet]
public string Value(int id)
{
return “value”;
}
[HttpPost]
public void SaveNewValue([FromBody]string value)
{
}
[HttpPut]
public void UpdateValue(int id, [FromBody]string value)
{
}
[HttpDelete]
public void RemoveValue(int id)
{
}
}
}
Web API Controller Characteristics
- It must be derived from System.Web.Http.ApiController class.
- It can be created under any folder in the project’s root folder. However, it is recommended to create controller classes in the Controllers folder as per the convention.
- Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.
- Return type of an action method can be any primitive or complex type. Learn more about it here.
Action Method Naming Conventions
As mentioned above, name of the action methods in the Web API controller plays an important role. Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above. However, you can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllNames(), GetStudents() or any other name which starts with Get.
The following table lists possible action method names for each HTTP method:
HTTP Method | Possible Web API Action Method Name | Usage |
GET | Get() get() GET() GetAllStudent() *any name starting with Get * | Retrieves data. |
POST | Post() post() POST() PostNewStudent() *any name starting with Post* | Inserts new record. |
PUT | Put() put() PUT() PutStudent() *any name starting with Put* | Updates existing record. |
PATCH | Patch() patch() PATCH() PatchStudent() *any name starting with Patch* | Updates record partially. |
DELETE | Delete() delete() DELETE() DeleteStudent() *any name starting with Delete* | Deletes record. |
The following figure illustrates the overall request/response pipeline.
Visit Web API HTTP Message Life Cycle Poster for more details.
Difference between Web API and MVC controller
Web API Controller | MVC Controller |
Derives from System.Web.Http.ApiController class | Derives from System.Web.Mvc.Controller class. |
Method name must start with Http verbs otherwise apply http verbs attribute. | Must apply appropriate Http verbs attribute. |
Specialized in returning data. | Specialized in rendering view. |
Return data automatically formatted based on Accept-Type header attribute. Default to json or xml. | Returns ActionResult or any derived type. |
Requires .NET 4.0 or above | Requires .NET 3.5 or above |
Configure Web API
Web API supports code based configuration. It cannot be configured in web.config file. We can configure Web API to customize the behaviour of Web API hosting infrastructure and components such as routes, formatters, filters, DependencyResolver, MessageHandlers, ParamterBindingRules, properties, services etc.
We created a simple Web API project in the Create Web API Project section. Web API project includes default WebApiConfig class in the App_Start folder and also includes Global.asax as shown below.
Global.asax
Copy
publicclass
WebAPIApplication
: System.Web.
HttpApplication
{
protected
void
Application_Start()
{
GlobalConfiguration
.Configure(
WebApiConfig.Register);
//other configuration
}
}
WebApiConfig
Copy
publicstatic
class
WebApiConfig
{
public
static
void
Register(
HttpConfigurationconfig)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name:
"DefaultApi",
routeTemplate:
"api/{controller}/{id}",
defaults:
new{ id = RouteParameter.Optional }
);
// configure additional webapi settings here..
}
}
Web API configuration process starts when the application starts. It calls GlobalConfiguration.Configure(WebApiConfig.Register)
in the Application_Start method. The Configure() method requires the callback method where Web API has been configured in code. By default this is the static WebApiConfig.Register() method.
As you can see above, WebApiConfig.Register()
method includes a parameter of HttpConfiguration
type which is then used to configure the Web API. The HttpConfiguration
is the main class which includes following properties using which you can override the default behaviour of Web API.
Property | Description |
DependencyResolver | Gets or sets the dependency resolver for dependency injection. |
Filters | Gets or sets the filters. |
Formatters | Gets or sets the media-type formatters. |
IncludeErrorDetailPolicy | Gets or sets a value indicating whether error details should be included in error messages. |
MessageHandlers | Gets or sets the message handlers. |
ParameterBindingRules | Gets the collection of rules for how parameters should be bound. |
Properties | Gets the properties associated with this Web API instance. |
Routes | Gets the collection of routes configured for the Web API. |
Services | Gets the Web API services. |
Web API Routing
In the previous section, we learned that Web API can be configured in WebApiConfig class. Here, we will learn how to configure Web API routes.
Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.
Web API supports two types of routing:
- Convention-based Routing
- Attribute Routing
Convention-based Routing
In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.
When we created Web API project using WebAPI template in the Create Web API Project section, it also added WebApiConfig class in the App_Start folder with default route as shown below.
Example: WebApiConfig with Default Route
Copy
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Add default route using convention-based routing
config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
}
}
In the above WebApiConfig.Register() method, config.MapHttpAttributeRoutes() enables attribute routing which we will learn later in this section. The config.Routes is a route table or route collection of type HttpRouteCollection. The “DefaultApi” route is added in the route table using MapHttpRoute() extension method. The MapHttpRoute() extension method internally creates a new instance of IHttpRoute and adds it to an HttpRouteCollection. However, you can create a new route and add it into a collection manually as shown below.
Example: Add Default Route
Copy
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
// define route
IHttpRoute defaultRoute = config.Routes.CreateRoute(“api/{controller}/{id}”,
new { id = RouteParameter.Optional }, null);
// Add route
config.Routes.Add(“DefaultApi”, defaultRoute);
}
}
The following table lists parameters of MapHttpRoute() method.
Parameter | Description |
name | Name of the route |
routeTemplate | URL pattern of the route |
defaults | An object parameter that includes default route values |
constraints | Regex expression to specify characteristic of route values |
handler | The handler to which the request will be dispatched. |
Now, let’s see how Web API handles an incoming http request and sends the response.
The following is a sample HTTP GET request.
Sample HTTP GET Request
GET http://localhost:1234/api/values/ HTTP/1.1
User-Agent: Fiddler
Host: localhost: 60464
Content-Type: application/json
Considering the DefaultApi route configured in the above WebApiConfig class, the above request will execute Get() action method of the ValuesController because HTTP method is a GET and URL is http://localhost:1234/api/values which matches with DefaultApi’s route template /api/{controller}/{id} where value of {controller} will be ValuesController. Default route has specified id as an optional parameter so if an id is not present in the url then {id} will be ignored. The request’s HTTP method is GET so it will execute Get() action method of ValueController.
If Web API framework does not find matched routes for an incoming request then it will send 404 error response.
The following figure illustrates Web API Routing.
The following table displays which action method and controller will be executed on different incoming requests.
Request URL | Request HTTP Method | Action method | Controller |
http://localhost:1234/api/course | GET | Get() | CourseController |
http://localhost:1234/api/product | POST | Post() | ProductController |
http://localhost:1234/api/teacher | PUT | Put() | TeacherController |
Note:
Web API also supports routing same as ASP.NET MVC by including action method name in the URL.
Configure Multiple Routes
We configured a single route above. However, you can configure multiple routes in the Web API using HttpConfiguration object. The following example demonstrates configuring multiple routes.
Example: Multiple Routes
Copy
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
// school route
config.Routes.MapHttpRoute(
name: “School”,
routeTemplate: “api/myschool/{id}”,
defaults: new { controller=”school”, id = RouteParameter.Optional }
constraints: new { id =”/d+” }
);
// default route
config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
}
}
In the above example, School route is configured before DefaultApi route. So any incoming request will be matched with the School route first and if incoming request url does not match with it then only it will be matched with DefaultApi route. For example, request url is http://localhost:1234/api/myschool is matched with School route template, so it will be handled by SchoolController.
Parameter Binding in ASP.NET Web API
In the previous section, we learned how Web API route an HTTP request to a controller and action method. Here, we will learn how Web API binds HTTP request data to the parameters of an action method.
Action methods in Web API controllers can have one or more parameters of different types. It can be either primitive type or complex type. Web API binds action method parameters with the URL’s query string or with the request body depending on the parameter type.
By default, if the parameter type is of .NET primitive types such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from string type, then it sets the value of a parameter from the query string. And if the parameter type is the complex type, then Web API tries to get the value from the request body by default.
The following table lists the default rules for parameter binding.
HTTP Method | Query String | Request Body |
GET | Primitive Type, Complex Type | NA |
POST | Primitive Type | Complex Type |
PUT | Primitive Type | Complex Type |
PATCH | Primitive Type | Complex Type |
DELETE | Primitive Type, Complex Type | NA |
Let’s see how Web API get values of action method parameters from the HTTP request.
Get Action Method with Primitive Parameter
Consider the following example of the GET
action method that includes a single primitive type parameter.
Example: Primitive Parameter Binding
Copy
publicclass
StudentController
:
ApiController
{
public
Student
Get(
intid)
{
}
}
As you can see, the above HTTP GET
action method includes the id
parameter of the int
type. So, Web API will try to extract the value of id from the query string of the requested URL, convert it into int and assign it to the id
parameter of the GET
action method. For example, if an HTTP request is http://localhost/api/student?id=1
then the value of the id
parameter will be 1.
The followings are valid HTTP GET
Requests for the above action method.
http://localhost/api/student?id=1
http://localhost/api/student?ID=1
Note:
Query string parameter name and action method parameter name must be the same (case-insensitive). If names do not match, then the values of the parameters will not be set. The order of the parameters can be different.
Multiple Primitive Parameters
Consider the following example of the GET
action method with multiple primitive parameters.
Example: Multiple Parameters Binding
Copy
publicclass
StudentController
:
ApiController
{
public
Student
Get(
intid,
stringname)
{
}
}
As you can see above, an HTTP GET
method includes multiple primitive type parameters. So, Web API will try to extract the values from the query string of the requested URL. For example, if an HTTP request is http://localhost/api/student?id=1&name=steve
, then the value of the id
parameter will be 1, and the name
parameter will be "steve"
.
Followings are valid HTTP GET Requests for the above action method.
http://localhost/api/student?id=1&name=steve
http://localhost/api/student?ID=1&NAME=steve
http://localhost/api/student?name=steve&id=1
Note:
Query string parameter names must match with the name of an action method parameter. However, they can be in a different order.
POST Action Method with Primitive Parameter
An HTTP POST
request is used to create a new resource. It can include request data into the HTTP request body and also in the query string.
Consider the following Post action method.
Example: Post Method with Primitive Parameter
Copy
publicclass
StudentController
:
ApiController
{
public
Student
Post(
idid,
stringname)
{
}
}
As you can see above, the Post()
action method includes primitive type parameters id and name. So, by default, Web API will get values from the query string. For example, if an HTTP POST request is http://localhost/api/student?id=1&name=steve
, then the value of the id
parameter will be 1 and the name
parameter will be "steve"
in the above Post()
method.
Now, consider the following Post()
method with the complex type parameter.
Example: Post Method with Complex Type Parameter
Copy
publicclass
Student
{
public
int
Id { get; set; }
public
string
Name { get; set; }
}
publicclass
StudentController
:
ApiController
{
public
Student
Post(
Studentstud)
{
}
}
The above Post()
method includes the Student
type parameter. So, as a default rule, Web API will try to get the values of the stud
parameter from the HTTP request body.
Following is a valid HTTP POST request in the fiddler for the above action method.
Web API will extract the JSON object from the HTTP request body above, and convert it into a Student
object automatically because the names of JSON object’s properties match with the name of the Student
class properties (case-insensitive).
POST Method with Mixed Parameters
The HTTP Post
action methods can include primitive and complex type parameters. Consider the following example.
Example: Post Method with Primitive and Complex Type Parameters
Copy
publicclass
Student
{
public
int
Id { get; set; }
public
string
Name { get; set; }
}
publicclass
StudentController
:
ApiController
{
public
Student
Post(
intage,
Studentstudent)
{
}
}
The above Post method includes both primitive and complex type parameters. So, by default , Web API will get the age
parameter from query string and student
parameter from the request body.
Following is a valid HTTP POST request in the fiddler for the above action method.
Note:
Post action method cannot include multiple complex type parameters because, at most, one parameter is allowed to be read from the request body.
Parameter binding for Put and Patch method will be the same as the POST
method in Web API.
[FromUri] and [FromBody]
You have seen that by default, ASP.NET Web API gets the value of a primitive parameter from the query string and a complex type parameter from the request body. But, what if we want to change this default behavior?
Use [FromUri]
attribute to force Web API to get the value of complex type from the query string and [FromBody]
attribute to get the value of primitive type from the request body, opposite to the default rules.
For example, consider the following GET
method.
Example: FormUri
Copy
publicclass
StudentController
:
ApiController
{
public
Student
Get([
FromUri]
Studentstud)
{
}
}
In the above example, the Get()
method includes a complex type parameter with the [FromUri]
attribute. So, Web API will try to get the value of the Student
type parameter from the query string. For example, if an HTTP GET request http://localhost:xxxx/api/student?id=1&name=steve
then Web API will create an object the Student
type and set its id
and name
property values to the value of id
and name
query string parameter.
Note:
The name of the complex type’s properties and the query string parameters must match.
Action Method Return Type
In the previous section, you learned about parameter binding with Web API action method. Here, you will learn about the return types of action methods which in turn will be embedded in the Web API response sent to the client.
The Web API action method can have following return types.
- Void
- Primitive type or Complex type
- HttpResponseMessage
- IHttpActionResult
Void
It’s not necessary that all action methods must return something. It can have void return type.
For example, consider the following Delete action method that just deletes the student from the data source and returns nothing.
Example: Void Return Type
Copy
public class StudentController : ApiController
{
public void Delete(int id)
{
DeleteStudentFromDB(id);
}
}
As you can see above Delete action method returns void. It will send 204 “No Content” status code as a response when you send HTTP DELETE request as shown below.
Primitive or Complex Type
An action method can return primitive or other custom complex types as other normal methods.
Consider the following Get action methods.
Example: Primitive or Complex Return Type
Copy
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class StudentController : ApiController
{
public int GetId(string name)
{
int id = GetStudentId(name);
return id;
}
public Student GetStudent(int id)
{
var student = GetStudentFromDB(id);
return student;
}
}
As you can see above, GetId action method returns an integer and GetStudent action method returns a Student type.
An HTTP GET request http://localhost:xxxx/api/student?name=john will return following response in Fiddler.
Primitive Return Type in Response
An HTTP GET request http://localhost:xxxx/api/student?id=1 will return following response in Fiddler.
Complex Return Type in Response
HttpResponseMessage
Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API request/response pipeline.
Visit Web API HTTP Message Life Cycle Poster for more details.
As you can see in the above figure, the Web API controller returns HttpResponseMessage object. You can also create and return an object of HttpResponseMessage directly from an action method.
The advantage of sending HttpResponseMessage from an action method is that you can configure a response your way. You can set the status code, content or error message (if any) as per your requirement.
Example: Return HttpResponseMessage
Copy
public HttpResponseMessage Get(int id)
{
Student stud = GetStudentFromDB(id);
if (stud == null) {
return Request.CreateResponse(HttpStatusCode.NotFound, id);
}
return Request.CreateResponse(HttpStatusCode.OK, stud);
}
In the above action method, if there is no student with specified id in the DB then it will return HTTP 404 Not Found status code, otherwise it will return 200 OK status with student data.
For example, an http GET request http://localhost:xxxx/api/student?id=100 will get following response considering student with id=100 does not exists in the DB.
The same way, an HTTP GET request http://localhost:60464/api/student?id=1 will get following response considering student with id=1 exists in the database .
IHttpActionResult
The IHttpActionResult was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.
You can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.
Example: Return IHttpActionResult Type using Ok() and NotFound() Methods
Copy
public IHttpActionResult Get(int id)
{
Student stud = GetStudentFromDB(id);
if (stud == null)
{
return NotFound();
}
return Ok(stud);
}
In the above example, if student with specified id does not exists in the database then it will return response with the status code 404 otherwise it sends student data with status code 200 as a response. As you can see, we don’t have to write much code because NotFound() and Ok() method does it all for us.
The following table lists all the methods of ApiController class that returns an object of a class that implements IHttpActionResult interface.
ApiController Method | Description |
BadRequest() | Creates a BadRequestResult object with status code 400. |
Conflict() | Creates a ConflictResult object with status code 409. |
Content() | Creates a NegotiatedContentResult with the specified status code and data. |
Created() | Creates a CreatedNegotiatedContentResult with status code 201 Created. |
CreatedAtRoute() | Creates a CreatedAtRouteNegotiatedContentResult with status code 201 created. |
InternalServerError() | Creates an InternalServerErrorResult with status code 500 Internal server error. |
NotFound() | Creates a NotFoundResult with status code404. |
Ok() | Creates an OkResult with status code 200. |
Redirect() | Creates a RedirectResult with status code 302. |
RedirectToRoute() | Creates a RedirectToRouteResult with status code 302. |
ResponseMessage() | Creates a ResponseMessageResult with the specified HttpResponseMessage. |
StatusCode() | Creates a StatusCodeResult with the specified http status code. |
Unauthorized() | Creates an UnauthorizedResult with status code 401. |
Visit MSDN to know all the members of ApiController.
Create Custom Result Type
You can create your own custom class as a result type that implements IHttpActionResult interface.
The following example demonstrates implementing IHttpActionResult class.
Example: Create Custom Result Type
Copy
public class TextResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request;
public TextResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
Now, you can return TextResult object from the action method as shown below.
Example: Return Custom Result Type
Copy
public IHttpActionResult GetName(int id)
{
string name = GetStudentName(id);
if (String.IsNullOrEmpty(name))
{
return NotFound();
}
return new TextResult(name, Request);
}
Web API Request/Response Data Formats
Here, you will learn how Web API handles different formats of request and response data.
Media Type
Media type (aka MIME type) specifies the format of the data as type/subtype e.g. text/html, text/xml, application/json, image/jpeg etc.
In HTTP request, MIME type is specified in the request header using Accept and Content-Type attribute. The Accept header attribute specifies the format of response data which the client expects and the Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.
For example, if a client wants response data in JSON format then it will send following GET HTTP request with Accept header to the Web API.
HTTP GET Request:
GET http://localhost:60464/api/student HTTP/1.1
User-Agent: Fiddler
Host: localhost:1234
Accept: application/json
The same way, if a client includes JSON data in the request body to send it to the receiver then it will send following POST HTTP request with Content-Type header with JSON data in the body.
HTTP POST Request:
POST http://localhost:60464/api/student?age=15 HTTP/1.1
User-Agent: Fiddler
Host: localhost:60464
Content-Type: application/json
Content-Length: 13
{
id:1,
name:'Steve'
}
Web API converts request data into CLR object and also serialize CLR object into response data based on Accept and Content-Type headers. Web API includes built-in support for JSON, XML, BSON, and form-urlencoded data. It means it automatically converts request/response data into these formats OOB (out-of the box).
Example: Post Action Method
Copy
publicclass
Student
{
public
int
Id { get; set; }
public
string
Name { get; set; }
}
publicclass
StudentController
:
ApiController
{
public
Student
Post(
Studentstudent)
{
// save student into db
var
insertedStudent = SaveStudent(student);
return
insertedStudent;
}
}
As you can see above, the Post() action method accepts Student type parameter, saves that student into DB and returns inserted student with generated id. The above Web API handles HTTP POST request with JSON or XML data and parses it to a Student object based on Content-Type header value and the same way it converts insertedStudent object into JSON or XML based on Accept header value.
The following figure illustrates HTTP POST request in fiddler.
In the above figure, Accept header specifies that it expects response data in XML format and Content-Type specifies that the student data into request body is in the JSON format. The following is the response upon execution of the above request.
The same way, you can specify different request & response format using accept and content-type headers and Web API will handle them without any additional changes.
The following HTTP POST request sends data in XML format and receives data in JSON format.
The above HTTP POST request will get the following response upon execution.
Thus, Web API handles JSON and XML data by default. Learn how Web API formats request/response data using formatters in the next section.
ASP.NET Web API: Media-Type Formatters
As you have seen in the previous section that Web API handles JSON and XML formats based on Accept and Content-Type headers. But, how does it handle these different formats? The answer is: By using Media-Type formatters.
Media type formatters are classes responsible for serializing request/response data so that Web API can understand the request data format and send data in the format which client expects.
Web API includes following built-in media type formatters.
Media Type Formatter Class | MIME Type | Description |
JsonMediaTypeFormatter | application/json, text/json | Handles JSON format |
XmlMediaTypeFormatter | application/xml, text/json | Handles XML format |
FormUrlEncodedMediaTypeFormatter | application/x-www-form-urlencoded | Handles HTML form URL-encoded data |
JQueryMvcFormUrlEncodedFormatter | application/x-www-form-urlencoded | Handles model-bound HTML form URL-encoded data |
Retrieve Built-in Media Type Formatters
As mentioned Web API includes above listed media type formatter classes by default. However, you can also add, remove or change the order of formatters.
The following example demonstrates HTTP Get method that returns all built-in formatter classes.
Example: Retrieve Built-in Formatters in C#
Copy
publicclass
FormattersController
:
ApiController
{
public
IEnumerable
<
string> Get()
{
IList
<
string> formatters =
newList
<
string>();
foreach
(
varitem
inGlobalConfiguration
.Configuration.Formatters)
{
formatters.Add(item.ToString());
}
return
formatters.AsEnumerable<
string>();
}
}
In the above example, GlobalConfiguration.Configuration.Formatters
returns MediaTypeFormatterCollection that includes all the formatter classes. The above example returns names of all the formatter classes as shown below.
Built-in Media-Type Formatters
Alternatively, MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example demonstrates retrieving media type formatters using MediaTypeFormatterCollection’s properties.
Example: Retrieve Built-in Formatters in C#
Copy
publicclass
FormattersController
:
ApiController
{
public
IEnumerable<
string> Get()
{
IList
<
string> formatters =
newList
<
string>();
formatters.Add(
GlobalConfiguration.Configuration.Formatters.JsonFormatter.GetType().FullName);
formatters.Add(
GlobalConfiguration.Configuration.Formatters.XmlFormatter.GetType().FullName);
formatters.Add(
GlobalConfiguration.Configuration.Formatters.FormUrlEncodedFormatter.GetType().FullName);
return
formatters.AsEnumerable<
string>();
}
}
The above example returns following response to the browser.
BSON Formatter
Web API also supports BSON format. As the name suggests, BSON is binary JSON, it is a binary-encoded serialization of JSON-like documents. Currently there is very little support for BSON and no JavaScript implementation is available for clients running in browsers. This means that it is not possible to retrieve and automatically parse BSON data to JavaScript objects.
Web API includes built-in formatter class BsonMediaTypeFormatter for BSON but it is disabled by default. Learn more about BSON support in Web API here.
JSON Formatter
As mentioned above, Web API includes JsonMediaTypeFormatter class that handles JSON format. The JsonMediaTypeFormatter converts JSON data in an HTTP request into CLR objects (object in C# or VB.NET) and also converts CLR objects into JSON format that is embeded within HTTP response.
Internally, JsonMediaTypeFormatter uses third-party open source library called Json.NET to perform serialization.
Configure JSON Serialization
JSON formatter can be configured in WebApiConfig class. The JsonMediaTypeFormatter class includes various properties and methods using which you can customize JSON serialization. For example, Web API writes JSON property names with PascalCase by default. To write JSON property names with camelCase, set the CamelCasePropertyNamesContractResolver on the serializer settings as shown below.
Example: Customize JSON Serialization in C#
Copy
public staticclass
WebApiConfig
{
public static void
Register(
HttpConfigurationconfig)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name:
"DefaultApi",
routeTemplate:
"api/{controller}/{id}",
defaults:
new{ id = RouteParameter.Optional }
);
// configure json formatter
JsonMediaTypeFormatter
jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver =
newCamelCasePropertyNamesContractResolver
();
}
}
XML Formatter
The XmlMediaTypeFormatter class is responsible for serializing model objects into XML data. It uses System.Runtime.DataContractSerializer class to generate XML data.
Web API Filters
Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.
Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.
The following table lists important interfaces and classes that can be used to create Web API filters.
Filter Type | Interface | Class | Description |
Simple Filter | IFilter | – | Defines the methods that are used in a filter |
Action Filter | IActionFilter | ActionFilterAttribute | Used to add extra logic before or after action methods execute. |
Authentication Filter | IAuthenticationFilter | – | Used to force users or clients to be authenticated before action methods execute. |
Authorization Filter | IAuthorizationFilter | AuthorizationFilterAttribute | Used to restrict access to action methods to specific users or groups. |
Exception Filter | IExceptionFilter | ExceptionFilterAttribute | Used to handle all unhandled exception in Web API. |
Override Filter | IOverrideFilter | – | Used to customize the behaviour of other filter for individual action method. |
As you can see, the above table includes class as well as interface for some of the filter types. Interfaces include methods that must be implemented in your custom attribute class whereas filter class has already implemented necessary interfaces and provides virtual methods, so that they can be overridden to add extra logic. For example, ActionFilterAttribute class includes methods that can be overridden. We just need to override methods which we are interested in, whereas if you use IActionFilter attribute than you must implement all the methods.
Visit MSDN to know all the classes and interfaces available in System.Web.Http.Filters.
Let’s create simple LogAttribute class for logging purpose to demonstrate action filter.
First, create a LogAttribute class derived from ActionFilterAttribute class as shown below.
Example: Web API Filter Class
Copy
publicclass
LogAttribute
:
ActionFilterAttribute
{
public
LogAttribute()
{
}
public
override
void
OnActionExecuting(
HttpActionContextactionContext)
{
Trace.WriteLine(
string.Format(
"Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
"Web API Logs");
}
public
override
void
OnActionExecuted(
HttpActionExecutedContextactionExecutedContext)
{
Trace.WriteLine(
string.Format(
"Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
"Web API Logs");
}
}
In the above example, LogAttribute is derived from ActionFilterAttribute class and overrided OnActionExecuting and OnActionExecuted methods to log in the trace listeners. (You can use your own logging class to log in textfile or other medium.)
Another way of creating LogAttribute class is by implementing IActionFilter interface and deriving Attribute class as shown below.
Example: Web API Filter Class
Copy
publicclass
LogAttribute
:
Attribute,
IActionFilter
{
public
LogAttribute()
{
}
public
Task
<
HttpResponseMessage> ExecuteActionFilterAsync(
HttpActionContextactionContext, CancellationToken cancellationToken,
Func<
Task<
HttpResponseMessage>> continuation)
{
Trace.WriteLine(
string.Format(
"Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
"Web API Logs");
var
result = continuation();
result.Wait();
Trace.WriteLine(
string.Format(
"Action Method {0} executed at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
"Web API Logs");
return
result;
}
public
bool
AllowMultiple
{
get {
returntrue
; }
}
}
In the above example, deriving from Attribute class makes it an attribute and implementing IActionFilter makes LogAttribute class as action filter. So now, you can apply [Log] attributes on controllers or action methods as shown below.
Example: Apply Web API Filter on Controller
Copy
[
Log]
publicclass
StudentController
:
ApiController
{
public
StudentController()
{
}
public
Student
Get()
{
//provide implementation
}
}
So now, it will log all the requests handled by above StudentController. Thus you can create filters for cross-cutting concerns.
Consume Web API in .NET using HttpClient
The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol. However, WebClient class had some limitations. The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient. Here, we will use HttpClient class in console application to send data to and receive data from Web API which is hosted on local IIS web server. You may use HttpClient in other .NET applications also such as MVC Web Application, windows form application, windows service application etc.
Let’s see how to consume Web API using HttpClient in the console application.
We will consume the following Web API created in the previous section.
Example: Web API Controller
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MyWebAPI.Controller
{
public
class
StudentController
:
ApiController
{
public
IHttpActionResult GetAllStudents(
boolincludeAddress =
false)
{
IList<StudentViewModel> students =
null;
using
(
varctx =
newSchoolDBEntities())
{
students = ctx.Students.Include(
"StudentAddress").Select(s =>
newStudentViewModel()
{
Id = s.StudentID,
FirstName = s.FirstName,
LastName = s.LastName,
Address = s.StudentAddress ==
null|| includeAddress ==
false?
null:
newAddressViewModel()
{
StudentId = s.StudentAddress.StudentID,
Address1 = s.StudentAddress.Address1,
Address2 = s.StudentAddress.Address2,
City = s.StudentAddress.City,
State = s.StudentAddress.State
}
}).ToList<StudentViewModel>();
}
if
(students.Count == 0)
{
return
NotFound();
}
return
Ok(students);
}
public
IHttpActionResult PostNewStudent(StudentViewModel student)
{
if
(!ModelState.IsValid)
return
BadRequest(
"Not a valid data");
using
(
varctx =
newSchoolDBEntities())
{
ctx.Students.Add(
newStudent()
{
StudentID = student.Id,
FirstName = student.FirstName,
LastName = student.LastName
});
ctx.SaveChanges();
}
return
Ok();
}
public
IHttpActionResult Put(StudentViewModel student)
{
if
(!ModelState.IsValid)
return
BadRequest(
"Not a valid data");
using
(
varctx =
newSchoolDBEntities())
{
var
existingStudent = ctx.Students.Where(s => s.StudentID == student.Id).FirstOrDefault<Student>();
if
(existingStudent !=
null)
{
existingStudent.FirstName = student.FirstName;
existingStudent.LastName = student.LastName;
ctx.SaveChanges();
}
else
{
return
NotFound();
}
}
return
Ok();
}
public
IHttpActionResult Delete(
intid)
{
if
(id <= 0)
return
BadRequest(
"Not a valid studet id");
using
(
varctx =
newSchoolDBEntities())
{
var
student = ctx.Students
.Where(s => s.StudentID == id)
.FirstOrDefault();
ctx.Entry(student).State = System.Data.Entity.EntityState.Deleted;
ctx.SaveChanges();
}
return
Ok();
}
}
}
Step 1:
First, create a console application in Visual Studio 2013 for Desktop.
Step 2:
Open NuGet Package Manager console from TOOLS -> NuGet Package Manager -> Package Manager Console and execute following command.
Install-Package Microsoft.AspNet.WebApi.Client
Step 3:
Now, create a Student model class because we will send and receive Student object to our Web API.
Example: Model Class
Copy
publicclass
Student
{
public
int
Id { get; set; }
public
string
Name { get; set; }
}
Send GET Request
The following example sends an HTTP GET request to Student Web API and displays the result in the console.
Example: Send HTTP GET Request using HttpClient
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace HttpClientDemo
{
class
Program
{
static
void
Main(
string[] args)
{
using
(
varclient =
newHttpClient())
{
client.BaseAddress =
newUri(
"http://localhost:60464/api/");
//HTTP GET
var
responseTask = client.GetAsync(
"student");
responseTask.Wait();
var
result = responseTask.Result;
if
(result.IsSuccessStatusCode)
{
var
readTask = result.Content.ReadAsAsync<Student[]>();
readTask.Wait();
var
students = readTask.Result;
foreach
(
varstudent
instudents)
{
Console.WriteLine(student.Name);
}
}
}
Console.ReadLine();
}
}
}
Let’s understand the above example step by step.
First, we have created an object of HttpClient and assigned the base address of our Web API. The GetAsync() method sends an http GET request to the specified url. The GetAsync() method is asynchronous and returns a Task. Task.wait() suspends the execution until GetAsync() method completes the execution and returns a result.
Once the execution completes, we get the result from Task using Task.result which is HttpResponseMessage. Now, you can check the status of an http response using IsSuccessStatusCode. Read the content of the result using ReadAsAsync() method.
Thus, you can send http GET request using HttpClient object and process the result.
Send POST Request
Similarly, you can send HTTP POST request using PostAsAsync() method of HttpClient and process the result the same way as GET request.
The following example send http POST request to our Web API. It posts Student object as json and gets the response.
Example: Send HTTP POST Request using HttpClient
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace HttpClientDemo
{
class
Program
{
static
void
Main(
string[] args)
{
var
student =
newStudent() { Name =
"Steve"};
var
postTask = client.PostAsJsonAsync<Student>(
"student", student);
postTask.Wait();
var
result = postTask.Result;
if
(result.IsSuccessStatusCode)
{
var
readTask = result.Content.ReadAsAsync<Student>();
readTask.Wait();
var
insertedStudent = readTask.Result;
Console.WriteLine(
"Student {0} inserted with id: {1}", insertedStudent.Name, insertedStudent.Id);
}
else
{
Console.WriteLine(result.StatusCode);
}
}
}
}
The following table lists all the methods of HttpClient to send different HTTP requests.
Method Name | Description |
GetAsync | Sends a GET request to the specified Uri as an asynchronous operation. |
GetByteArrayAsync | Sends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation. |
GetStreamAsync | Sends a GET request to the specified Uri and returns the response body as a stream in an asynchronous operation. |
GetStringAsync | Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation. |
PostAsync | Sends a POST request to the specified Uri as an asynchronous operation. |
PostAsJsonAsync | Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON. |
PostAsXmlAsync | Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as XML. |
PutAsync | Sends a PUT request to the specified Uri as an asynchronous operation. |
PutAsJsonAsync | Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON. |
PutAsXmlAsync | Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as XML. |
DeleteAsync | Sends a DELETE request to the specified Uri as an asynchronous operation. |
Configure Dependency Injection with Web API
Here you will learn how to configure and use IoC container for dependency injection with Web API.
There are many IoC containers available for dependency injection such as Ninject, Unity, castleWidsor, structuremap etc. Here we will use Ninject for dependency injection.
The following is our sample Web API that uses instance of a class that implements IRepository.
Example: Simple Web API Controller
Copy
publicclass
StudentController
:
ApiController
{
private
IRepository
_repo =
null;
public
StudentController(
IRepositoryrepo)
{
_repo = repo;
}
public
IList
<
Student> Get()
{
return
_repo.GetAll();
}
}
The following are IRepository and StudentRepository class.
Example: Repository
Copy
publicinterface
IRepository
{
IList
<
Student> GetAll();
}
publicclass
StudentRepository
:
IRepository
{
public
IList
<
Student> GetAll()
{
//return students from db here
}
}
Now, let’s use Ninject which will inject StudentRepository class in StudentController.
First of all, you need to install Ninject library for Web API using NuGet. To do this, right click on your project in the solution explorer -> click on Manage NuGet packages... This will open NuGet popup. Now search for webapicontrib in the search box as shown below.
As you can see, this will list all the IoC containers for Web API. Select WebApiContrib.IoC.Ninject and click Install.
Now, you need to install Ninject.Extensions.ChildKernel. Search for it and install it.
So now after installing necessary packages for Ninject, we need to configure it.
In order to use dependency injection with Web API, we need to create a resolver class that implements IDependencyResolver interface. Here, we have created NinjectResolver class in Infrastructure folder in our Web API project as shown below.
Example: DI Resolver
Copy
publicclass
NinjectResolver
:
IDependencyResolver
{
private
IKernel
kernel;
public
NinjectResolver() :
this(
newStandardKernel
())
{
}
public
NinjectResolver(
IKernelninjectKernel,
boolscope =
false)
{
kernel = ninjectKernel;
if
(!scope)
{
AddBindings(kernel);
}
}
public
IDependencyScope
BeginScope()
{
return
new
NinjectResolver
(AddRequestBindings(
newChildKernel
(kernel)),
true);
}
public
object
GetService(
TypeserviceType)
{
return
kernel.TryGet(serviceType);
}
public
IEnumerable
<
object> GetServices(
TypeserviceType)
{
return
kernel.GetAll(serviceType);
}
public
void
Dispose()
{
}
private
void
AddBindings(
IKernelkernel)
{
// singleton and transient bindings go here
}
private
IKernel
AddRequestBindings(
IKernelkernel)
{
kernel.Bind<
IRepository>().To<
StudentRepository>().InSingletonScope();
return
kernel;
}
}
Now, we need to configure NijectResolver with Web API in the WebApiConfig class as shown below.
Example: Set DI Resolver
Copy
publicstatic
class
WebApiConfig
{
public
static
void
Register(
HttpConfigurationconfig)
{
config.DependencyResolver =
newNinjectResolver
();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name:
"DefaultApi",
routeTemplate:
"api/{controller}/{id}",
defaults:
new{ id = RouteParameter.Optional }
);
}
}
As you can see above, HttpConfiguration.DependencyResolver is set to NinjectResolver. So now, Web API will use NinjectResolver class to create the objects it needs.
Thus, you can configure IoC container with Web API.
Web API Hosting
In this section, you will learn how to host a Web API.
The Web API application can be hosted in two ways.
- IIS Hosting
- Self Hosting
IIS Hosting
Web API can be hosted under IIS, in the same way as a web application. You have learned to create a Web API in the previous section. As you have seen there, a Web API is created with ASP.NET MVC project by default. So, when you host your MVC web application under IIS it will also host Web API that uses the same base address.
Self Hosting
You can host a Web API as separate process than ASP.NET. It means you can host a Web API in console application or windows service or OWIN or any other process that is managed by .NET framework.
You need to do following steps in order to self-host a web API.
- Use HttpConfiguration to configure a Web API
- Create HttpServer and start listening to incoming http requests
Let’s see how to host a simple Web API in console application.
First of all, create a console project in Visual Studio 2012 for Desktop (or latter version).
Note: You must open Visual Studio in Administration mode.
Now, you need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet. Right click on project in the Solution Explorer window and select Manage NuGet Packges..
In the Manage NuGet Packages window, select Online option in left pan and search for web-api. This will list all the packages for Web API. Now, look for Microsoft ASP.NET Web API 2.2 Self Host package and click Install.
Install Web API Self Host Package
Click on Accept button in the License Acceptance window.
This will install the package into your project.
Install Web API self Hosting Package
Now write the following code in the Main() method of Program class.
Example: Self-Hosting Web API
Copy
class Program
{
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration(“http://localhost:1234”);
var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());
var task = server.OpenAsync();
task.Wait();
Console.WriteLine(“Web API Server has started at http://localhost:1234”);
Console.ReadLine();
}
}
In the above code, first we created an object of HttpSelfHostConfiguration class by passing uri location. Then, we created an object of HttpSelfHostServer by passing config and HttpMessageHandler object. And then we started listening for incoming request by calling server.OpenAsync() method. This will listen requests asynchronously, so it will return Task object.
Create MyWebAPIMessageHandler class and write the following code.
Example: MessageHandler
Copy
class MyWebAPIMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var task = new Task<HttpResponseMessage>(() => {
var resMsg = new HttpResponseMessage();
resMsg.Content = new StringContent(“Hello World!”);
return resMsg;
});
task.Start();
return task;
}
}
Thus, you can create simple console application and host simple Web API that returns “Hello World!” to every request.
Run the console application using Ctrl + F5.
Open web browser and enter http://localhost:1234/ and see the result.
Hosting Controller Infrastructure
You can use the same ASP.NET routing and ApiController capabilities of ASP.NET Hosting in self hosting.
In the same self hosting console application, create simple HomeController class as shown below.
Example: Web API Controller
Copy
public class HomeController : ApiController
{
public string Get() {
return “Hello World!”;
}
public string Get(string name) {
return “Hello ” + name;
}
}
Now, in the Main() method, configure a default route using config object as shown below.
Example: Self Hosting Web API
Copy
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration(“http://localhost:1234”);
config.Routes.MapHttpRoute(“default”,
“api/{controller}/{id}”,
new { controller = “Home”, id = RouteParameter.Optional });
var server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
Console.WriteLine(“Web API Server has started at http://localhost:1234”);
Console.ReadLine();
}
Please notice that we removed an object of MessageHandler when creating an object of HttpSelfHostServer.
Now, run the console application by pressing Ctrl + F5. Open the browser and enter http://localhost:1234/api or http://localhost:1234/api?name=steve and see the result as shown below.
Web API Interview Questions
1. What is ASP.Net Web API?
A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP-based services. 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 queues, one-way messaging, and duplex communication. WEB API supports any media format, even XML and JSON, while WCF supports SOAP and XML formats. 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.
3. What are the advantages of using ASP.Net Web API?
A: The advantages of using ASP.Net Web API are mentioned below:
- It completes support for routing
- Is works as HTTP using standard HTTP verbs such as GET, DELETE, POST, PUT, to name a few, for all CRUD operations
- It can be hosted in IIS as well as self-host outside of IIS
- It supports OData
- It supports validation and model binding
- The response is generated in XML or JSON format by using MediaTypeFormatter
4. What are the several return types in ASP.Net Web API?
A: The various return types in ASP.Net Web API are:
- IHttpActionResult
- HttpResponseMessage
- Void
- Other Type – string, int, or other entity types.
5. What is ASP.Net Web API routing?
A: It is the process that determines the action and controller that should be called.
The ways to incorporate routing in Web API include:
- Attribute based routing
- Convention based routing
6. What are Media type formatters in Web API?
A: The Media type formatter in Web API include:
- MediaTypeFormatter – It is the base class that helps to handle serializing and deserializing strongly-typed objects.
- BefferedMediaTypeFormatter – It signifies a helper class to allow asynchronous formatter on top of the asynchronous formatter infrastructure.
7. What is the CORS issue in Web API?
A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin restriction for JavaScript. Same-origin means 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.
Open WebAPIConfig.cs file
add config.EnableCors();
Add EnableCors attribute to the Controller class and define the origin.
[EnableCors(origins: “”, headers: “*”, methods: “*”)].
8. How to secure an ASP.Net Web API?
A: To secure an ASP.Net Web API, we need to control the Web API and decide who 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?
A: GET and POST are two important verbs of HTTP.
- 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
10. How can Web API be used?
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.
11.Exception filters in ASP.Net Web API
A: Exception filters in Web API help in implementing IExceptionFilters interface. They perform when an action throws an exception at any point.
12. Do we return Views from ASP.Net Web API?
A: No, it is not possible as Web API creates an HTTP-based service. It is mostly available in the MVC application.
13. What is new in ASP.Net Web API 2.0?
A: The features introduced in ASP.NET Web API framework v2.0 are:
- Attribute Routing
- External Authentication
- CORS (Cross-Origin Resource Sharing)
- OWIN (Open Web Interface for .NET) Self Hosting
- IHttpActionResult
- Web API Odata
14. How do we limit access to methods with an HTTP verb in Web API?
A: An attribute has to be added as shown below:
[HttpGet]
public HttpResponseMessage Test()
{
HttpResponseMessage response = new HttpResponseMessage();
///
return response;
}
[HttpPost]
public void Save([FromBody]string value)
{
}
15. 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”))
To learn JSON format, you can also take up free online courses that will help you enhance your basic skills about the same.
16. How to provide Alias name for an action method in Web API?
A: By adding an attribute ActionName, an Alias name can be provided:
[ActionName(“InertUserData”)]
// POST api/
public void Post([FromBody]string value)
{
}
17. How can we handle errors in Web 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.
18. How to host Web API?
A: There are two ways how Web API application can be hosted:
- Self Hosting
- IIS Hosting
19. How to consume Web API using HTTPClient?
A: HTTPClient is introduced in HTTPClient class for communicating with ASP.Net Web API. This HTTPClient class is used either in a console application or in an MVC application.
20. Explain oData with ASP.Net Web API.
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 operations. 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
21. Can we consume Web API 2 in C# console application?
A: Yes, Web API 2 can be consumed in Console Application, MVC, Angular JS, or any other application.
22. Perform Web API 2 CRUD operation using Entity Framework.
A: CRUD operation can be performed by using entity framework with Web API.
23. How to enable HTTPs in 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.
24. How to implement Basic Authentication in ASP.Net Web API?
A: Basic Authentication in ASP.Net Web API can be implemented where the client sends a request with an Authorization header and the word Basic. In Basic Authentication, the Authorization header contains the word Basic followed by a base 64 encoded string.
The syntax for Basic Authentication –
1 | Authorization: Basic username: password |
25. What is Token Based Authentication in Web API?
A: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-based approach.
26. What is content negotiation in .Net Web API?
A: In ASP.Net Web API, content negotiation is done on the server side. This helps in determining the media type formatter, especially when it is about returning the response to an incoming request.
27. What is ASP.Net identity?
A: ASP.Net identity is the membership management framework that Microsoft provides. It is very easily incorporated with Web API. This can help you to build a secure HTTP service.
28. What is Bearer Authentication in .Net Web API?
A: Bearer authentication is also known as Token-based authentication.
29. 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.
30. What is Not REST?
A: The mentioned below are not REST:
- A standard
- A protocol
- 3. A replacement of SOAP
31. What are the differences between REST and SOAP?
A: Here are some differences between REST and SOAP:
SOAP | REST |
SOAP stands for Simple Object Access Protocol | REST stands for Representational State Transfer. |
SOAP is a protocol, called an XML | REST is not a protocol but you can call it an architectural pattern example which is used for resource-based architecture. |
SOAP specifies both stateless as well as state-full implementation | REST is completely stateless. |
SOAP applies message formats like XML; | REST does not apply message formats like XML or JSON. |
To expose the service, SOAP uses interfaces and named operations; | REST uses URI and methods like POST, GET, PUT, and DELETE for exposing resources (service). |
32. What are the differences between ASP.NET MVC and ASP.NET Web API?
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.
33. Is it true that ASP.NET Web API has replaced WCF?
A: It is not true! It is rather just another way to build non-SOAP-based services like plain XML or JSON strings. It comes with additional advantages such as using HTTP’s full features and reaching more clients such as mobile devices, etc.
34. Explain media Formatters in Web API 2
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.
35. 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.
36. What are the similarities between MVC and Web API?
A: Both MVC and Web API are based on the principle of Separation of concerns and concepts like controllers, routing, and models.
37. What are the differences between MVC and Web API?
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.
38. Who can consume Web API?
A: Web API is consumed by a client that supports HTTP verbs such as DELETE, GET, PUT, and 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.
39. How are Requests mapped to Action methods in Web API?
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:
$.get(“/api/Employees/1”, null, function(response)
{
$(“#employees”).html(response);
});
Therefore, the method name above has no mention. As an alternative, GetEmployee method can be called by using the GET HTTP verb.
The GetEmployee method can be defined as:
[HttpGet]
public void GetEmployee(int id)
{
StudentRepository.Get(id);
}
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
40. Can the HTTP request be mapped to the action method without using the HTTP attribute?
A: For the action method, there are two ways to map the HTTP request. The first way is using the trait on the action method. The second way is naming the method that starts with the HTTP verb. Taking as an example, to define a GET method, can be defined as:
public void GetEmployee(int id)
{
StudentRepository.Get(id);
}
As it can start with GET, the above-mentioned method can be automatically mapped with the GET request.
41. How to add certificates to a website?
A: To add the certificate to the website, you can follow the steps mentioned below:
- You have to go to run type command mmc
- Now click on Ok
- The certificate add window is open now
42. Write a LINQ code for authenticating the user?
A: public static bool Login(string UN, string pwd)
{StudentDBEntities students = new StudentDBEntities()students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // students has more than one table}
43. How to navigate another page in jQuery?
A: using widow.location.href = “~/homw.html”;
44. How to enable SSL to ASP.NET web?
A: In order to enable SSL to ASP.NET web, you can click on project properties where you can see this option.
45. How to mention Roles and users using Authorize attribute in Web API?
// Restrict by Name
[Authorize(Users=”Shiva,Jai”)]
public class StudentController : ApiController{}
// Restrict by Role[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController{}
46. Can we apply constraints at the route level?
A: Yes, it can be applied.
[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.
47. How to enable attribute routing?
A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the WebApi config file.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
48. How parameters get the value in Web API?
A: Parameters get value in Web API in the following way:
- Request body
- URI
- Custom Binding
49. Why is the “api/” segment used in Web API routing?
A: “api/” segment is used to avoid collisions with ASP.NET MVC routing
50. Is it possible to have MVC kind of routing in Web API?
A: It is possible to implement MVC kind of routing in Web API.
51. Where is the route defined in Web API?
A: It is placed in the App_Start directory.
App_Start –> WebApiConfig.cs
routes.MapHttpRoute(
name: “myroute”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
52. How do you construct HtmlResponseMessage?
public class TestController : ApiController
A: To construct HtmlResponseMessage, you can consider the following way:
{
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;
}
}
53. What are the default media types supported by Web API?
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.
54. What is the disadvantage of “Other Return Types” in Web API?
A: The major disadvantage of “Other Return Types” in Web API is that error codes like 404 errors will not directly be returned.
55. What is the namespace for IHttpActionResult return type in Web API?
A: System.Web.Http.Results namespace
56. Why is Web API important?
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.
57. Which .NET framework supports Web API?
The .NET framework version supported by Web API includes version 4.0 and above.
58. Which open-source library is supported by Web API for JSON serialization?
JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API.
59. What are the advantages of using REST in Web API?
REST offers numerous advantages in Web API that include –
- Lightweight architecture and easy to use
- Offers flexibility
- Allows less data transfer between client and server
- Handles various types of data formats
- Its lightweight architecture makes it optimal for use in mobile applications
- Uses simple HTTP calls for inter-machine communication
60. When do we need to choose ASP.NET Web API?
We are moving web-based services toward mobile applications in today’s hyper-connected digital world. That means we need a lightweight, secure, safe, and compatible API with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by many clients, including browsers and modern devices such as mobile phones, tablets, etc.
61. What do you understand by TestApi in Web API?
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.
62. 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.
63. Can we consume Web API 2 in the C# console application?
Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any other application.
64. How to implement Basic Authentication in ASP.Net Web API?
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.
The syntax for Basic Authentication –
Authorization: Basic username: password
65. Give an example of the parameter in Web API.
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 –
public IHttpActionResult GetProductMaster(int id)
{
ProductMaster productMaster = db.ProductMasters.Find(id);
if (productMaster == null)
{
return NotFound();
}
return Ok(productMaster);
}
In the same way, the Post method will require complex type parameters to post data to the server.
public IHttpActionResult PostProductMaster(ProductMaster productMaster)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.ProductMasters.Add(productMaster);
db.SaveChanges();
return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster);
}
Similarly PUT method will require primitive data type example for id and complex parameter i.e. ProductMaster class.
if (id != productMaster.id)
{
return BadRequest();
}
db.Entry(productMaster).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductMasterExists(id))
{
return NotFound();
}
else
{
throw;
}
}
66. Give an example to specify Web API Routing.
Here is an example of Web API routing –
Config.Routes.MapHttpRoute(
name: “MyRoute,”//route name
routeTemplate: “api/{controller}/{action}/{id}”,//as you can see “API” is at the beginning.
defaults: new { id = RouteParameter.Optional }
);
67. How to register an exception filter globally?
You can use the following code to register an exception filter globally –
GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());
68. What are the different HTTP methods used in Web API?
Though there are a variety of HTTP verbs or methods, the most important and frequently used ones are GET, PUT, POST and DELETE.
GET – It is used to retrieve information of the resource at a specified URI.
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 –
C stands for Create or POST (creating data)
R stands for Read or GET (data retrieval)
U stands for Update or PUT (updating data)
D stands for Delete or DELETE (deleting data)
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.
69. What is HttpConfiguration in Web API?
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
70. Explain the code snippet to show how we can return 404 errors from HttpError.
Here’s the Code for returning 404 error from HttpError –
string message = string.Format(“TestCustomer id = {0} not found”, customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
71. What is the code used to register an exception filter from the action?
One can register an exception filter using the following code –
[NotImplExceptionFilter]
public TestCust GetMyTestCust (int custno)
{
//write the code
}
72. What are the testing tools or API for developing or testing web API?
- CFX
- Axis
- Jersey API
- Restlet
73. How can you pass multiple complex types in Web API?
Two ways to pass multiple complex types in Web API include – Newtonsoft array and using ArrayList.
74. What is the code for passing ArrayList in .NET Web API?
ArrayList paramList = new ArrayList();
Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};
Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p);
75. What is an HTTP status code?
HTTP status codes are three-digit integers issued by the server in response to the request made by the client, where each number specifies a meaning.
76. How are different HTTP Status Codes categorized?
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.
77. What is the commonly observed HTTP response status code?
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 –
- Status code 200 – request is ok.
- Status code 201 – Created
- Status code 202 – Accepted
- Status code 204 – No content
- Status code 301 – Moved permanently
- Status code 400 – Bad request
- Status code 401 – Unauthorized
- Status code 403 – Forbidden
- Status code 404 – Not found
- Status code 500 – Internal server error
- Status code 502 – Bad gateway
- Status code 503 – Service Unavailable
78. How do website owners avoid HTTP status codes?
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 an 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.
79. Name method that validates all controls on a page?
Page.Validate() method system is executed to validate all controls on a page.
80. What is the use of DelegatingHandler?
DelegatingHandler is a process used to develop a custom server-side HTTP message handler in ASI.Net Web API and chain message handlers together.
81. What do you mean by Internet Media Types?
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,
Image– type/png- subtype
Application– type/rss- subtype+xml
82. Can a Web API return an HTML View?
Web API cannot return an HTML view. If you want to return views, it is best to use MVC.
83. 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.
84. Can you elaborate on different Web API filters?
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.
85. What is the difference between ApiController and Controller?
ApiController specializes in returning data arranged in series and sent to the client.
public class TweetsController : ApiController
{
// GET: /Api/Tweets/
public List<Tweet> Get()
{
return Twitter.GetTweets();
}
}
Controller, on the other hand, provides normal views and handles HTTP requests.
public class TweetsController : Controller
{
// GET: /Tweets/ [HttpGet] public ActionResult Index()
{
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
86. What is the difference between XML and JSON?
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.
87. What do you mean by Caching?
Caching refers to the technique of storing data in temporary storage in a cache for future use. It keeps copies of all frequently used data and 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 needed.
The simplest cache in ASP.Net Web API is based on IMemoryCache.
Some key advantages of Caching include –
- Minimizes database hits
- Helps web pages render faster
- Reduces network costs
- Faster execution of process
- Highly efficient for both client and server
- Reduces load time on the server
- Best page management strategy to improve application’s performance
88. What are the types of Caching?
There are different types of caching in ASP.NET Web API. These are –
- 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.
Here’s the code to implement page output caching –
<%@ OutputCache Duration=”30″ VaryByParam=”*” %>
- 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”;
Web API FAQs
What is Web API and how it works?
A web API is an interface that allows you to access and manipulate data over the internet. It is typically used to access data from a web server, and can be used to create web applications or websites. It can be developed with the help of different technologies such as ASP.NET, or Java.
What is Web API in C# ?
A programming interface type that provides communication between software applications. It is often used to provide the interface for client applications and websites. It can also be used to access and save data from a database.
What are the types of API?
There are mainly four types of API used for web-applications. They are as follows:
– public,
– partner,
– private, and
– composite.
What is Web API example?
The full form of API is Application Programming Interface and it can extend the functionality of a web browser. An API would allow a third party such as Facebook to directly access the various functions of an external application, such as ordering a product on Amazon.
Why do we need Web API to develop RESTful services as we can also develop RESTful services using WCF?
Yes, it is absolutely possible to develop RESTful services using WCF (Windows Communication Foundation). But there are few reasons why people are moving from WCF to WEB API for developing restful services. Some of them are as follows.
- The Web API increases the TDD (Test Driven Development) approach in the development of RESTful services.
- If we want to develop RESTful services using WCF, then we need to do a lot of configuration settings, URI templates, contracts & endpoints. WCF basically used to develop SOA (Service Oriented Architecture) based applications.
What are the important return types supported in ASP.NET Web API?
In ASP.NET Web API Application, the controller action methods can return the following:
- Void – It simply returns empty content
- HttpResponseMessage – It will convert the response message to an HTTP message.
- IHttpActionResult – It internally calls the ExecuteAsync method to create an HttpResponseMessage
- Other types – You can also write the serialized return value into the response body. For example, you want to return Excel files.
Which .NET framework supports Web API?
The .NET Framework 4.0 and above version supports ASP.NET Web API.
Which protocol ASP.NET Web API supports?
The ASP.NET Web App supports the one and only HTTP protocol.
ASP.NET Web API uses which open-source library for JSON serialization?
The ASP.NET Web API Framework uses the Json.NET library for JSON serialization.
By default, Web API sends an HTTP response with which status code for an uncaught exception?
It will send the response with HTTP Status 500 – Internal Server Error
How do you construct HtmlResponseMessage in ASP.NET Web API?
public class HomeController : 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;
}
}
What is Routing in ASP.NET Web API?
The ASP.NET Web API Routing module is responsible for mapping the incoming HTTP requests to a particular controller action method. Based on the incoming requests the Web API uses URI and HTTP verbs to select the action method. Please read our Routing in ASP.NET Web API article for more detail.
How the Web API Framework handle an incoming HTTP Request?
When the ASP.NET Web API Framework receives an HTTP request, it tries to match the URI against one of the route templates available in the routing table. If no route template matches the URI, then Web API Framework returns a 404 error to the client who actually makes the request. Once a matching route is found in the Route Table, the Web API Framework then selects the controller and the action to be executed.
What is SOAP?
SOAP stands for Simple Object Access Protocol and it is an XML-based protocol. SOAP has specifications for both stateless and state-full implementation. It is also an XML-based messaging protocol for exchanging information among computers. The SOAP message consists of an envelope that includes SOAP headers and body to store the actual information we want to send. It supports different types of protocols such as HTTP, TCP, etc.
How Can we assign an alias name for ASP.NET Web API Action?
We can give alias name for Web API action using the “ActionName” attribute as follows:
[HttpPost]
[ActionName(“StudentAdd”)]
public void AddStudents(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}
For more detail about default naming convention and custom action names, please read our Custom Action Name article.
What is Content Negotiation in Web API?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. One of the standards of the REST service is that the client should have the ability to decide in which format they want the response – whether they want the response in XML or JSON etc. This is called Content Negotiation in Web API. Web API Content Negotiation means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. That’s why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. Please read our Web API Content Negotiation article where we discussed this concept in detail with examples.
What is CORS?
Before understanding CORS, first, we need to understand the same-origin policy. Browsers allow a web page to make AJAX requests only within the same domain. The Browsers does not allow a web page from making AJAX requests to another domain. This is called the same-origin policy.
CORS is a W3C standard that allows us to get away from the same-origin policy adopted by the browsers that restrict access from making AJAX requests from one domain to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use). Please read our Cross-Origin Resource Sharing (CORS) in Web API article where we discussed this concept in detail with examples.
What is Web API Attribute Routing?
The ASP.NET Web API 2 supports a new type of routing called attribute routing. Attribute routing means attributes are used to define routes. The Attribute routing provides more control over the URIs by defining routes directly on the actions and controllers. Please read our Attribute Routing in Web API article where we discussed this concept in detail with examples.
Why do we need Attribute Routing in Web API?
The convention-based routing makes it hard to support certain URI patterns that are common in RESTful APIs. For example, resources often contain child resources such as Customers have orders, movies have actors, books have authors, etc. It’s natural to create URIs that reflect these relations.
What is Authentication and Authorization in Web API?
Once you create a Web API Service, then the most important thing that you need to take care of is security means you need to control access to your Web API Services.
Authentication is the process of identifying the user. For example, one user let’s say James logs in with his username and password, and the server uses his username and password to authenticate James.
Authorization is the process of deciding whether the authenticated user is allowed to perform an action on a specific resource (Web API Resource) or not. For example, James (who is an authenticated user) has the permission to get a resource but does not have the permission to create a resource. Please read our Authentication and Authorization in ASP.NET Web API article where we discussed this concept in detail with examples.
What is an HTTP Message handler in ASP.NET Web API Application?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. An HTTP Message Handler in Web API is a class that receives an HTTP request and returns an HTTP response. The Message Handler is derived from the abstract HttpMessageHandler class. The HTTP Message handlers are good for cross-cutting concerns (such as authentication and authorization) that operate at the level of HTTP messages rather than controller actions. For example, a Custom HTTP Message handler might do the following things in a Web API Application.
- Read or modify the HTTP request headers.
- Add a response header to the HTTP response.
- Validate the requests before they reach the controller (i.e. Authentication and Authorization).
Please read our HTTP Message Handler in the Web API article where we discussed this concept in detail with multiple real-time examples.
Why Web API versioning is required?
Once you develop and deploy a Web API service then different clients start consuming your Web API services. As you know, day by day the business grows and once the business grows then the requirement may change, and once the requirement change then you may need to change the services as well, but the important thing you need to keep in mind is that you need to do the changes to the services in such a way that it should not break any existing client applications who already consuming your services.
This is the ideal scenario when the Web API versioning plays an important role. You need to keep the existing services as it is so that the existing client applications will not break, they worked as it is, and you need to develop a new version of the Web API service which will start consuming by the new client applications. Please read our Web API Versioning article where we discussed this concept in detail with examples.
What are the Different options available in Web API to maintain the versioning?
The different options that are available to maintain versioning are as follows
- URI’s
- Query String
- Version Header
- Accept Header
- Media Type
What are Request Verbs or HTTP Verbs?
In RESTful service, we can perform all types of CRUD (Create, Read, Update, Delete) Operation. In REST architecture, it is suggested to have a specific Request Verb or HTTP verb on the specific type of the call made to the server. Popular Request Verbs or HTTP Verbs are mentioned below:
- HTTP GET: This HTTP verb is Used to get the resource only.
- HTTP POST: This HTTP verb is Used to create a new resource.
- HTTP PUT: This HTTP verb is Used to update an existing resource.
- HTTP PATCH: This HTTP verb is Used to update an existing resource.
- HTTP DELETE: This HTTP verb is Used to Delete an existing resource.
Note: PUT and PATCH are not similar. If you are updating few columns in your database then use PATCG and if you are updating all the data then use PUT.
What do you mean by Parameter Binding in Web API?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The Parameter Binding means how the Web API Framework binds the incoming HTTP request data to the parameters of an action method of a Web API controller. The ASP.NET Web API action methods can take one or more parameters of different types. An action method parameter can be either of a complex type or primitive type. The Web API Framework binds the action method parameters either with the URL’s query string or from the request body of the incoming HTTP Request based on the parameter type.
By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string. And if the action method parameter type is a complex type then Web API Framework tries to get the value from the request body.
But we can change this default behavior of the parameter binding process by using [FromBody] and [FromUri] attributes.
- FromBody: This will force the Web API Framework to get the value from the request body.
- FromUri: This will force the Web API Framework to get the data from the URI (i.e. Route data or Query String)
Please read our Parameter Binding in ASP.NET Web API article where we discussed this concept in detail with examples.
What is the use of Authorize Attribute?
The ASP.NET Web API Framework provided a built-in authorization filter, i.e. Authorize Attribute. This filter checks whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.
How to Enable CORS in Web API?
If we are going to consume the ASP.NET Web API Service using Jquery Ajax from another domain, then we need to enable CORS in the Web API application. Without enabling CORS, it is not possible to access the service from another domain using AJAX call. Enabling CORS in Web API is a two steps process.
Step1: Install Microsoft.AspNet.WebApi.Cors package.
Step2: Once you installed the Microsoft.AspNet.WebApi.Corspackage then includes the following 2 lines of code in the Register() method of WebApiConfig class which is present inside the App_Start folder of your project.
EnableCorsAttribute cors = new EnableCorsAttribute(“*”, “*”, “*”);
config.EnableCors();
What is Basic HTTP Authentication?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client needs to pass the username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password: based encoded. Please read our Basic Authentication in ASP.NET Web API article where we discussed this concept in detail with examples.
What is ASP.Net identity?
ASP.Net identity is the membership management framework given by Microsoft which can be easily integrated with ASP.NET Web API. This helps us in building a secure HTTP service.
What is Token Based Authentication in Web API?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Nowadays, the use of Web API is increasing in a rapid manner. So as a developer we should know how to develop Web APIs. Only developing Web APIs is not enough if there is no security. So, it also very important to implement security for all types of clients (such as Browsers, Mobile Devices, Desktop applications, and IoTs) who are going to use our Web API services.
The most preferred approach nowadays to secure the Web API resources is by authenticating the users in the Web API server by using the signed token (which contains enough information to identify a particular user) which needs to be sent to the server by the client in each and every request. This is called the Token-Based Authentication approach.
How does the Token-Based Authentication work?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. In order to understand how token-based authentication works, please have a look at the following diagram.
The Token-Based Authentication works as Follows:
- The user enters his credentials (i.e. the username and password) into the client (here client means the browser or mobile devices, etc).
- The client then sends these credentials (i.e. username and password) to the Authorization Server.
- Then the Authorization Server authenticates the client credentials (i.e. username and password) and generates and returns an access token. This Access Token contains enough information to identify a user and also contains the token expiry time.
- The client application then includes the Access Token in the Authorization header of the HTTP request to access the restricted resources from the Resource Server until the token is expired.
Please read our Token Based Authentication in Web API article where we discussed this concept in detail with examples.
What is a Refresh Token?
A Refresh Token is a special kind of token that can be used to obtain a new renewed access token that allows access to the protected resources. You can request the new access tokens by using the Refresh Token in Web API until the Refresh Token is blacklisted.
Why we need Refresh Token in Web API?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The idea of using the refresh token is to issue a short-lived access token (up to 30 minutes) for the first time and then use the refresh token to obtain a new access token and use that access token to access the protected resources.
So, the user needs to provide the username and password along with the client info (i.e. the client id and client secret) to authenticate himself, and if the information provided by the user is valid, then a response contains a short-lived access token along with a long-lived refresh token gets generated.
The refresh token is not an access token it is just an identifier for the access token. Now once the access token is expired, the user can use the refresh token to obtain another short-lived access token and so on.
Please read our Refresh Token in the Web API article where we discussed this concept in detail with examples.
What is HMAC Authentication?
This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The HMAC stands for Hash-based Message Authentication Code. From the full form of HMAC, we need to understand two things one is Message Authentication Code and the other one is Hash-Based. So HMAC is a mechanism that is used for creating a Message Authentication Code by using a Hash Function.
The most important thing that we need to keep in mind is that while generating the Message Authentication Code using Hash Function we need to use a Shared Secret Key. Moreover, the Shared Secret Key must be shared between the Client and the Server involved in sending and receiving the data.
Why do we need HMAC Authentication in Web API?
The main uses of HMAC Authentication in Web API are as follows.
- Data integrity: It means the data sent by the client to the server has not tampered.
- Request origination: The request comes to the server from a trusted client.
- Not a replay request: The request is not captured by an intruder and being replayed.
Thank you for sharing your info. I truly appreciate
your efforts and I am waiting for your further post thanks once again.
I’ll right away grab your rss as I can not find your email subscription link or
e-newsletter service. Do you have any? Please let me recognize so that I may just subscribe.
Thanks.
This is my first time go to see at here and i am truly pleassant to read everthing at single place.
my web blog … KASACKS DAMEN
Hi! Do you use Twitter? I’d like to follow you if that would be okay.
I’m undoubtedly enjoying your blog and look forward to new posts.
Multimedia Engineering
Informatics Engineering
Internet Engineering
Language Center
International Studies
Electronics Engineering
telecoms
electrical engineering
computer engineering
I have learn a few excellent stuff here. Certainly worth bookmarking for revisiting.
I surprise how a lot effort you place to create this kind of magnificent informative website.
Howdy would you mind stating which blog platform you’re using?
I’m going to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different
then most blogs and I’m looking for something unique.
P.S My apologies for getting off-topic but I had to ask!
Also visit my webpage :: KASACK
Piece of writing writing is also a fun, if you know then you can write or else it is difficult to write.
I used to be able to find good advice from
your articles.
Nice post. I was checking continuously this blog and I am impressed!
Very useful information particularly the last part
🙂 I care for such information much. I was looking for this certain information for a very long time.
Thank you and good luck.
I got this site from my pal who shared with me on the topic of this web site and at
the moment this time I am visiting this web page and reading very informative posts at this place.
mʏ pge :: @SEOGAPCHAT telegram seo group for GuestPosting
Ϝeell frtеe ttо viit my websitе; @SEOGAPCHAT telegram seo group with high DA
Feеel frеe too viisit mmy Ƅlpg post Mehran Yousefi
Have you ever considered about adding a little bit more
than just your articles? I mean, what you
say is important and all. Nevertheless think about if you added some great images or video clips to give your posts more,
“pop”! Your content is excellent but with images and
videos, this site could definitely be one of the most beneficial in its field.
Superb blog!
Great information. Lucky me I came across your site by accident (stumbleupon).
I’ve bookmarked it for later!
Thanks a lot for your feedback.
I’m impressed, I must say. Seldom do I come across a blog that’s equally educative and entertaining,
and without a doubt, you’ve hit the nail on the head. The problem
is something that not enough people are speaking intelligently about.
I am very happy I came across this during my search for something regarding this.
Wow, wonderful blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your site
is fantastic, let alone the content!
What’s up everybody, here every person is sharing these experience, therefore it’s nice to read this
weblog, and I used to go to see this web site daily.
Enhance your allure and spark unforgettable
connections. Discover the essence of attraction, confidence, and romance with our
unique blend designed for vibrant, passionate moments.
Ignite your charm and let chemistry work its magic. Feel the difference, feel the desire.
Наша команда квалифицированных мастеров завершена предоставлять вам перспективные приемы, которые не только ассигнуруют прочную протекцию от холода, но и подарят вашему собственности элегантный вид.
Мы трудимся с последовательными веществами, заверяя долгий продолжительность службы и великолепные выходы. Изолирование облицовки – это не только экономия тепла на подогреве, но и забота о экосистеме. Сберегательные технологии, каковые мы внедряем, способствуют не только жилищу, но и сохранению природных ресурсов.
Самое ключевое: Сколько стоит утепление фасада у нас стартует всего от 1250 рублей за м²! Это доступное решение, которое изменит ваш домашний уголок в реальный тепловой уголок с минимальными затратами.
Наши труды – это не единственно теплоизоляция, это составление площади, в где каждый деталь символизирует ваш личный стиль. Мы примем во внимание все твои желания, чтобы осуществить ваш дом еще больше дружелюбным и привлекательным.
Подробнее на http://www.ppu-prof.ru
Не откладывайте заботу о своем корпусе на потом! Обращайтесь к экспертам, и мы сделаем ваш жилище не только согретым, но и моднее. Заинтересовались? Подробнее о наших трудах вы можете узнать на сайте компании. Добро пожаловать в сферу удобства и уровня.
I’ve been browsing online more than 3 hours these days, yet I by no means discovered any interesting article
like yours. It’s beautiful price enough for me. Personally, if all webmasters and bloggers made just right
content as you probably did, the internet will be a lot more helpful
than ever before.
thanks a lot for your feedback.
Excellent article. I will be experiencing a few of these issues as well..
This site was… how do you say it? Relevant!!
Finally I have found something which helped me. Appreciate it!
Thanks for finally writing about > Asp.Net Web API with 50
Plus Interview Questions – DotNet < Liked it!
Thanks a lot for your feedback.
Its like you read my thoughts! You seem to grasp so much about this, like you wrote
the ebook in it or something. I believe that you just could do with some p.c.
to force the message house a little bit, but instead of that, this is wonderful blog.
A great read. I’ll definitely be back.
Sample Templates –
Sample Template – Excel Template –
Best Template – Free Sample Templates –
Download Templates – Mustervorlagen – BestTemplatess
Look into my web site … Kleurplaten
Thanks a lot for your feedback.
great issues altogether, you just received a new reader. What could you suggest in regards to your put up that you made a few days ago?
Any sure?
Thanks a lot for your feedback.
Excellent beat ! I would like to apprentice whilst you amend your website, how can i subscribe for a weblog website?
The account helped me a applicable deal. I had been a little bit familiar of this your
broadcast provided brilliant clear concept
Thanks a lot for your feedback.
I blog often and I truly thank you for your content. This great article has really peaked
my interest. I am going to book mark your site and keep checking for new information about once a week.
I opted in for your RSS feed too.
Thanks a lot for your feedback.
I’m truly enjoying the design and layout of your blog.
It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did
you hire out a developer to create your theme?
Outstanding work!
Thanks a lot for your feedback.
I do believe all of the concepts you have introduced to your post.
They’re very convincing and can certainly work. Nonetheless,
the posts are too brief for starters. Could you please extend them a
little from subsequent time? Thank you for the post.
Thanks a lot for your feedback.
I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored
material stylish. nonetheless, you command get bought an shakiness
over that you wish be delivering the following.
unwell unquestionably come further formerly again as exactly the same nearly a lot
often inside case you shield this hike.
Thanks a lot for your feedback.
Hello to every body, it’s my first visit of this webpage; this blog
contains amazing and genuinely good data designed for visitors.
Thanks a lot for your feedback.
It is the best time to make some plans for the future
and it is time to be happy. I have read this post and if I could I desire to suggest you some interesting things or tips.
Perhaps you could write next articles referring to this article.
I want to read more things about it!
Thanks a lot for your feedback.
Yes sure you can suggest
Hi to every one, the contents existing at this site are
truly remarkable for people experience, well, keep up the good work fellows.
Thanks a lot for your feedback.
What’s Taking place i am new to this, I stumbled upon this I’ve
discovered It positively helpful and it has helped me out loads.
I am hoping to give a contribution & help other users like its aided me.
Good job.
Thanks a lot for your feedback.
constantly i used to read smaller posts that as well clear their motive, and that is also happening with this article which I am
reading now.
Thanks a lot for your feedback.
Great delivery. Sound arguments. Keep up the great effort.
Thanks a lot for your feedback.
Hi there would you mind sharing which blog platform you’re working with?
I’m looking to start my own blog soon but I’m
having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design seems different then most blogs and I’m looking
for something unique. P.S Apologies for
being off-topic but I had to ask!
Hi @syair Thanks a lot for your feedback.
This is custom theme from wordpress.
Nicce post. I learn something nnew and challenging on blogs
I stumbleupon everyday. It’s always useful to read articlrs from
other writers and practice a little something from their
sites. https://Www.Waste-Ndc.pro/community/profile/tressa79906983/
Thanks a lot for your feedback.
Touche. Great arguments. Keep up the good work.
Take a look at my web page – PFLEGE KASACKS
Logo Design Bundaberg by Roundhouse, Address: A1088/157B Bourbong St, Bundaberg Central QLD 4670, Australia, Email: bundaberg@roundhouse.cc, Phone: +61 1300 727 749, Url: https://www.hellolisting.com.au/agriculture/other-services_1/logo-design-bundaberg-by-roundhouse-i32012
I blog often and I seriously thank you for your information. Your article has really peaked my interest.
I am going to bookmark your site and keep checking for new details about once a week.
I opted in for your Feed as well.
I love the way you offered either side on the argument in a good and unbiased way. It is really unusual to check out that volume of objectivity lately.
Your publish is an excellent starting point for any person searching To find out more about this issue.
Your web site happens to be a Portion of my regime. I am unable to get ample!
is there a generic advair
I do trust all the concepts you have offered to your post.
They are really convincing and can definitely work. Still, the posts are too short for
novices. May just you please prolong them a bit from subsequent time?
Thank you for the post.
I have been adhering to your blog for some time now, and it retains getting better. https://matters.town/a/6dhvz1mp1ii3
Hey there, I love all the points you made on that topic. There is definitely a great deal to know about this subject, and with that said, feel free to visit my blog Webemail24 to learn more about Blogging.
This provider offers some of the best high risk payment processors, ensuring your business transactions are handled securely.
Link pyramid, tier 1, tier 2, tier 3
Tier 1 – 500 links with integration inside articles on article domains
Middle – 3000 link Redirected connections
Tier 3 – 20000 hyperlinks combination, feedback, entries
Implementing a link hierarchy is advantageous for search engines.
Necessitate:
One connection to the site.
Keywords.
Correct when 1 key phrase from the resource topic.
Highlight the extra offering!
Vital! Primary connections do not conflict with 2nd and 3rd-tier links
A link structure is a instrument for elevating the circulation and inbound links of a internet domain or social network
Be affected person and constant together with your hyperlink building efforts,
and you will note your webpage’s search engine
rating improve over time.
Take a look at my web blog :: backlinks wat zijn – http://www.google.sm
–
The Significance of Resonance Management Tools in Industrial Equipment
Within manufacturing sites, equipment along with spinning devices serve as the backbone of manufacturing. However, an of the most widespread problems that might obstruct its efficiency and durability is vibrations. Oscillation may result in an series of issues, such as reduced accuracy along with productivity resulting in heightened deterioration, ultimately leading to costly downtime along with fixes. This is when vibration regulation apparatus proves to be necessary.
The Reason Vibration Management is Important
Resonance within machinery may bring about various harmful consequences:
Lowered Operational Productivity: Excess vibration can cause misalignments and imbalance, lowering the efficiency of such devices. Such a scenario can lead to reduced output times as well as higher energy consumption.
Greater Wear and Tear: Continuous vibration hastens overall damage in equipment components, bringing about additional maintenance and an potential of unexpected unexpected breakdowns. Such a scenario not only increases production expenses as well as shortens the lifetime of your equipment.
Safety Hazards: Excessive vibrations can bring considerable safety concerns for the machinery and the machinery and the personnel. In extreme situations, extreme situations, such vibrations may result in catastrophic equipment failure, endangering personnel and causing significant devastation to the site.
Precision and Quality Concerns: For businesses that require high precision, such as manufacturing and aerospace, vibration could bring about discrepancies in manufacturing, resulting in faulty goods as well as greater waste.
Cost-effective Approaches for Vibration Control
Investing into resonance control equipment remains not only essential but a sound investment for any business involved with machines. Our state-of-the-art vibration management systems are designed to mitigate vibrations from various mechanical systems as well as rotating machinery, ensuring smooth along with efficient operations.
Something that distinguishes our apparatus apart remains its cost-effectiveness. We understand the significance of affordability in the current market, thus our offerings include high-quality vibration control solutions at prices that won’t break the bank.
Through selecting our offerings, you are not just preserving your machines and enhancing its efficiency but also putting resources in the long-term success of your business.
In Conclusion
Vibration control is an essential element of maintaining the operational performance, safety, and lifespan of your industrial equipment. With these reasonably priced resonance mitigation apparatus, one can be certain your production run smoothly, your products are of high quality, and your workers stay safe. Don’t permit vibrations jeopardize your company—make an investment in the correct apparatus now.
B1088/157B Bourbong St, Bundaberg Central QLD 4670, Australia – The Website Design Bundaberg by Roundhouse team collaborates closely with you to understand your brand and target audience. We utilize cutting-edge design and technology to create websites that are mobile-responsive, optimized for search engines, and deliver a seamless user experience. Whether you’re a startup or a seasoned business, Website Design Bundaberg is your partner for online success in Bundaberg.