1. What is ASP.NET Web API?
ASP.NET Web API is a framework that simplifies the creation of HTTP services
WebAPI is a framework which helps you to build/develop HTTP services.
ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework.
Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including:
- Create resource-oriented services using the full features of HTTP
- Exposing services to a variety of clients easily like browsers or mobile devices, etc.
Apart from Visual Studio 2010 or 2012, we also need MVC 4.0 to implement this HTTP service. For the purpose of this implementation, I am going to use Visual Studio 2010.
You can download MVC 4.0 for Visual Studio 2010 from Microsoft.
You can download MVC 4.0 for Visual Studio 2010 from Microsoft.
Following are 3 simple steps to create HTTP service that returns non-SOAP based data.
- Create Web API Project
- Prepare domain Model
- Adding Controller class
You are designing an ASP.NET Web API application. You need to select an HTTP verb to allow blog administrators to moderate a comment. Which HTTP verb should you use?
- A. GET
- B. POST
- C. DELETE
- D. PUT
WebAPI provides your OrderController with out-of-the-box support for the following URLs:
HTTP Verb | URL | Description |
---|---|---|
GET | /api/order | Returns all orders |
GET | /api/order/3 | Returns details order #3 |
POST | /api/order | Create new order |
PUT | /api/order/3 | Update order #3 |
DELETE | /api/order/3 | Delete order #3 |
The above is considered verb-based routing. The URLs above only contain the controller name and an optional id. So the Web API uses the HTTP verb of the request to determine the action method to execute in your ApiController subclass.
->
Why Asp.Net Web API faster than WCF?
WCF was created to develop SOAP-based services and bindings. Since WCF is SOAP-based, which uses standard XML schema over HTTP, it could lead to slower performance. WEB API is a better choice for simpler, lightweight services. WEB API can use any text format including XML and is faster than WCF. WEB API doesn’t require any data contracts and doesn’t require configurations to the level of WCF.
->>
->>
Web API concepts in different fields and Its implementation using Asp.Net MVC and Entity Framework . Web API Controller connects with Sql Server by Entity Framework. Web API Route can be used in different types of clients Like IOTs. ASP.NET Web API is a framework for building Web API’s, i.e. HTTP based services on top of the .NET Framework. The most common use case for using Web API is for building RESTful services.It has a great role for IOTs stands for Internet Of Things.
WEB API is a best fit to create a resource-oriented services using HTTP/Restful and it works well with MVC-based applications.WEB API can use any text format including XML and is faster than WCF.
Description
WEB API is a best fit to create a resource-oriented services using HTTP/Restful and it works well with MVC-based applications.WEB API can use any text format including XML and is faster than WCF.
Description
These Web API services can then be Used by below mentioned lists,
- Browsers
- Mobile applications
- Desktop applications
In Client-Server constraint, Client sends a request and the server sends a response. This separation of concerns supports the independent evolution of the client-side logic and server-side logic. In Stateless constraint, the client and the server must be stateless between requests. This means we should not be storing anything on the server related to the client. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.
In Cacheable constraint, the client knows how long this data is good for so that the client does not have to come back to the server for that data over and over again. In Uniform Interface The HTTP verb like GET, PUT, POST, DELETE that is sent with each request tells the API what to do with the resource. Each resource is identified by a specific URI stands for Uniform Resource Identifier.
2. What are the Advantages of Using ASP.NET Web API?
Using ASP.NET Web API has a number of advantages, but core of the advantages are:
- It works the HTTP way using standard HTTP verbs like
GET
,POST
,PUT
,DELETE
, etc. for all CRUD operations - Complete support for routing
- Response generated in JSON or XML format using
MediaTypeFormatter
- It has the ability to be hosted in IIS as well as self-host outside of IIS
- Supports Model binding and Validation
- Support for OData
- and more....
For implementation on performing all CRUD operations using ASP.NET Web API, click here.
3. What New Features are Introduced in ASP.NET Web API 2.0?
More new features introduced in ASP.NET Web API framework v2.0 are as follows:
- Attribute Routing
- External Authentication
- CORS (Cross-Origin Resource Sharing)
- OWIN (Open Web Interface for .NET) Self Hosting
IHttpActionResult
- Web API OData
You can follow a good Web API new feature details on Top 5 New Features in ASP.NET Web API 2 here.
4. WCF Vs ASP.NET Web API?
Actually, Windows Communication Foundation is designed to exchange standard SOAP-based messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ, etc.
On the other hand, ASP.NET API is a framework for building non-SOAP based services over HTTP only.
For more details, please follow here.
5. Is it True that ASP.NET Web API has Replaced WCF?
It's a misconception that ASP.NET Web API has replaced WCF. It's another way of building non-SOAP based services, for example, plain XML or JSON string, etc.
Yes, it has some added advantages like utilizing full features of HTTP and reaching more clients such as mobile devices, etc.
But WCF is still a good choice for following scenarios:
- If we intended to use transport other than HTTP, e.g. TCP, UDP or Named Pipes
- Message Queuing scenario using MSMQ
- One-way communication or Duplex communication
For a good understanding for WCF(Windows Communication Foundation), please follow WCF Tutorial.
6. MVC Vs ASP.NET Web API?
As in previous ASP.NET Web API Interview Questions, we discussed that the purpose of Web API framework is to generate HTTP services that reach more clients by generating data in raw format, for example, plain XML or JSON string. So, ASP.NET Web API creates simple HTTP services that renders raw data.
On the other hand, ASP.NET MVC framework is used to develop web applications that generates Views as well as data. ASP.NET MVC facilitates in rendering HTML easy.
For ASP.NET MVC Interview Questions, follow the link.
7. How to Return View from ASP.NET Web API Method?
(A tricky Interview question) No, we can't return view from ASP.NET Web API method. We discussed in the earlier interview question about the difference between ASP.NET MVC and Web API that ASP.NET Web API creates HTTP services that renders raw data. Although, it's quite possible in ASP.NET MVC application.
8. How to Restrict Access to Web API Method to Specific HTTP Verb?
Attribute programming plays its role here. We can easily restrict access to an ASP.NET Web API method to be called using a specific HTTP method. For example, we may require in a scenario to restrict access to a Web API method through HTTP
POST
only as follows:
Hide Copy Code
[HttpPost]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}
9. Can we use Web API with ASP.NET Web Form?
Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be used with ASP.NET Web Form.
It can be done in three simple steps as follows:
- Create a Web API Controller
- Add a routing table to
Application_Start
method of Global.asax - Make a jQuery AJAX Call to Web API method and get data
jQuery call to Web API for all CRUD (Create, Retrieve, Update, Delete) operations can be found here.
10. How Can We Provide an Alias Name for ASP.NET Web API Action?
We can provide an alias name for ASP.NET Web API action same as in case of ASP.NET MVC by using "
ActionName
" attribute as follows:
Hide Copy Code
[HttpPost]
[ActionName("SaveStudentInfo")]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}
In this ASP.NET Tutorial, we covered the most important Interview questions on ASP.NET Web API framework. Hopefully, it will be helpful for Web API developer Interview but along with these questions, do the practical implementation as much as you can. In Practical guide to ASP.NET Web API, you can find a good step by step approach for understanding and implementing ASP.NET Web API services.
11) Why is Web API required? Is it possible to use RESTful services using WCF?
Yes, we can still develop RESTful services with WCF. However, there are two main reasons that prompt users to use Web API instead of RESTful services.
- Web API increases TDD (Test Data Driven) approach in the development of RESTful services.
- If we want to develop RESTful services in WCF, you surely need a lot of config settings, URI templates, contracts & endpoints for developing RESTful services instead of web API.
12) Why select Web API?
- It is used to create simple, non-SOAP-based HTTP Services
- It is based on HTTP and easy to define, expose and consume in a REST-ful way.
- It is lightweight architecture and ideal for devices that have limited bandwidth like smartphones.
14) Is it right that ASP.NET Web API has replaced WCF?
It’s a not at all true that ASP.NET Web API has replaced WCF. In fact, it is another way of building non-SOAP based services, i.e., plain XML or JSON string.
15) What are the advantages of Web API?
Advantages of Web API are:
- OData
- Filters
- Content Negotiation
- Self-Hosting
- Routing
- Model Bindings
16) What are main return types supported in Web API?
A Web API controller action can return following values:
- Void – It will return empty content
- HttpResponseMessage – It will convert the response to an HTTP message.
- IHttpActionResult – internally calls ExecuteAsync to create an HttpResponseMessage
- Other types – You can write the serialized return value into the response body
17) Web API supports which protocol?
Web App supports HTTP protocol.
18) Which .NET framework supports Web API?
NET 4.0 and above version supports web API.
NET 4.0 and above version supports web API.
19) Web API uses which of the following open-source library for JSON serialization?
Web API uses Json.NET library for JSON serialization.
20) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
500 – Internal Server Error
21) What is the biggest disadvantage of “Other Return Types” in Web API?
The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.
22) How do you construct HtmlResponseMessage?
Following is the way to construct to do so,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("Testing", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
}
|
13) What is Web API Routing?
Routing is pattern matching like in MVC.
All routes are registered in Route Tables.
For example:
14) What is SOAP?
SOAP is an XML message format used in web service interactions. It allows to send messages over HTTP or JMS, but other transport protocols can be used. It is also an XML-based messaging protocol for exchanging information among computers.
15) What is the benefit of using REST in Web API?
REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps. Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication.
16) How can we use Web API with ASP.NET Web Form?
Web API can be used with ASP.NET Web Form
It can be performed in three simple steps:
- Create a Web API Controller,
- Add a routing table to Application_Start method of Global.sax
- Then you need to make a jQuery AJAX Call to Web API method and get data.
17) How to you can limit Access to Web API to Specific HTTP Verb?
Attribute programming plays a important role. It is easy to restrict access to an ASP.NET Web API method to be called using a particular HTTP method.
18) Can you use Web API with ASP.NET Web Form?
Yes, It is possible to use Web API with ASP.Net web form. As it is bundled with ASP.NET MVC framework. However, it can be used with ASP.NET Web Form.
19) How Can assign alias name for ASP.NET Web API Action?
We can give alias name for Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:
20) What is the meaning of TestApi?
TestApi is a utility library of APIs. Using this library tester developer can create testing tools and automated tests for a .NET application using data-structure and algorithms.
21) Explain exception filters?
It will be executed when exceptions are unhandled and thrown from a controller method. The reason for the exception can be anything. Exception filters will implement “IExceptionFilter” interface.
22) How can we register exception filter from the action?
We can register exception filter from action using following code:
23) How you can return View from ASP.NET Web API method?
No, we can’t return a view from ASP.NET Web API Method. Web API creates HTTP services that render raw data. However, it’s also possible in ASP.NET MVC application.
24) How to register exception filter globally?
It is possible to register exception filter globally using following code-
GlobalConfiguration.Configuration.Filters.Add(new MyTestCustomerStore.NotImplExceptionFilterAttribute());
25) Explain what is REST and RESTFUL?
REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.
RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system resources and how the state of the resource should be transported over HTTP protocol.
26) Give me one example of Web API Routing?
27) How can you handle errors in Web API?
Several classes are available in Web API to handle errors. They are HttpError, Exception Filters, HttpResponseException, and Registering Exception Filters.
28) What New Features comes with ASP.NET Web API 2.0?
The latest features of ASP.NET Web API framework v2.0 are as follows:
- Attribute Routing
- Cross-Origin Resource Sharing
- External Authentication
- Open Web Interface NET
- HttpActionResult
- Web API OData
29) How can you restrict access methods to specific HTTP verbs in Web API?
With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web API.
It is possible to define HTTP verbs as an attribute to restrict access.
Example:
30) How can you pass multiple complex types in Web API?
Two methods to pass the complex types in Web API –
Using ArrayList and Newtonsoft array
31) Write a code for passing ArrayList in Web API?
32) Name the tools or API for developing or testing web api?
Testing tools for web services for REST APIs include:
- Jersey API
- CFX
- Axis
- Restlet
33) What is REST?
REST is architectural style. It has defined guidelines for creating services which are scalable. REST used with HTTP protocol using its verbs GET, PUT, POST and DELETE.
34) How to unit test Web API?
We can perform a Unit test using Web API tools like Fiddler.
Here, are some setting to be done if you are using
Fiddler –Compose Tab -> Enter Request Headers -> Enter the Request Body and execute
35) How can we restrict access to methods with specific HTTP verbs in Web API?
Attribute programming is widely used for this functionality. Web API also allows restricting access of calling methods with the help of specific HTTP verbs. It is also possible to define HTTP verbs as attribute over method.
36) What is the usage of DelegatingHandler?
DelegatingHandler is used in the Web API to represent Message Handlers before routing.
37) How can we register exception filter from the action?
We can register exception filter from action using following code
38) Tell me the code snippet to show how we can return 404 errors from HttpError?
Code for returning 404 error from HttpError
string message = string.Format(“TestCustomer id = {0} not found”, customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
39) Explain code snippet to register exception filters from controller?
40) Web API supports which protocol?
Web App support HTTP protocol
41) Which of the following .NET framework supports Web API?
Web API is supported by NET 4.0 version
42) Web API uses which library for JSON serialization?
Web API uses Json.NET library for JSON serialization.
43) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
500 – Internal Server Error
44) Explain method to handle error using HttpError in Web API?
In WEB API HttpError used to throw the error info in the response body. “CreateErrorResponse” method is can also use along with this, which is an extension method defined in “HttpRequestMessageExtension.”
45) How can we register exception filter globally?
We can register exception filter globally using following code:
46) How to handle errors in Web API?
Several classes are available in Web API to handle errors. They are HttpError, HttpResponseException, Exception Filters, Registering Exception Filters.
47) What is the benefit of WebAPI over WCF?
WCF services use the SOAP protocol while HTTP never use SOAP protocol. That’s why WebAPI services are lightweight since SOAP is not used. It also reduces the data which is transferred to resume service. Moreover, it never needs too much configuration. Therefore, the client can interact with the service by using the HTTP verbs.
48) State differences between MVC and WebAPI
MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.
WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.
49) Who can consume WebAPI?
WebAPI can be consumed by any client which supports HTTP verbs such as GET, PUT, DELETE, POST. As WebAPI services don’t need any configuration, they are very easy to consume by any client. Infract, even portable devices like Mobile devices can easily consume WebAPI which is certainly the biggest advantages of this technology.
50) How can we make sure that Web API returns JSON data only?
To make Web API serialize the returning object to JSON format and returns JSON data only. For that you should add the following code in WebApiConfig.cs class in any MVC Web API Project:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//JsonFormatter
//MediaTypeHeaderValue
Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
1
2
3
//JsonFormatter
//MediaTypeHeaderValue
Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))
|
--------------------------------------------------------
Are you working on a REST API and using the new Web API to implement it? You’ve written an ApiController subclass or two? Let’s say you’ve created a new subclass of ApiController called OrderController. WebAPI provides your OrderController with out-of-the-box support for the following URLs:
HTTP Verb | URL | Description |
---|---|---|
GET | /api/order | Returns all orders |
GET | /api/order/3 | Returns details order #3 |
POST | /api/order | Create new order |
PUT | /api/order/3 | Update order #3 |
DELETE | /api/order/3 | Delete order #3 |
The above is considered verb-based routing. The URLs above only contain the controller name and an optional id. So the Web API uses the HTTP verb of the request to determine the action method to execute in your ApiController subclass.
Your Goal
Now what if you want to add some custom actions to your ApiController subclass? For example:
HTTP Verb | URL | Description |
---|---|---|
GET | api/order/3/vendors | Returns all vendors involved with providing items to complete order #3 |
PUT | /api/order/3/expedite | Expedites order #3, but can only be executed by managers in customer service dept. |
PUT | /api/order/3/reject | Rejects order #3, but can only be executed by managers in customer service dept. |
It turns out that adding those custom actions is hard, very hard. But keep reading. There is an easy way.
The Problem and Existing Solutions
We need to be able to mix verb-based routing and action-name based routing in our controller subclass. If you start a search for possible solutions, you will find a bug report in the public Web API tracker along with an issue in the Web API user voice, both of which say it isn’t immediately possible.
If you read those issues along with an associated forum post, the solutions mentioned range from writing a custom IRouteHandler, custom IHttpControllerSelector or custom IHttpActionSelector. All of those options are a bit complicated, just to add a simple custom action to your existing controller.
I’m going to show you a much simpler solution. But if you want to use a custom action selector to solve this problem, there is great blog post you should read.
The Simpler Way
Now let’s see what we’d like the new Vendors and Reject action to look like on the Order Controller:
If you take the above code, compile and run it, you will not be able to execute either of the new actions.
Like ASP.NET MVC, the first step when debugging Web API routes and actions is to look at the Route Configuration. Below is the default route configuration found in App_Start/WebApiConfig.cs
As you can see, the routeTemplate argument does not include “{action}” which means the action variable will never be set. The action selector has to pick an action method without the action variable, so of course it never executes our new actions.
We need to update the routeTemplate to indicate where in the URL to find the {action}variable So, we change the routeTemplate to: “api/{controller}/{id}/{action}“. But, now {action} is required for all URLs. We can’t require {action} for all URLs, it needs to be optional for /api/order/3
There are two ways to make {action} optional. The first method is using the defaults arguments and setting action to RouteParameter.Optional. This method of making {action} optional won’t work for us, it will result in an ambiguous actions error. We need to use the second method, which is hard-coding a default value if {action} isn’t provided in the URL.
If you compile and run the web application, you will find that all of the original routes return an error message of: No action was found on the controller ‘Order’ that matches the name ‘DefaultAction’. We are going to skip testing of the new Vendors and Rejectroutes for the moment.
How we can name those original routes to have a name of ‘DefaultAction’? It turns out WebAPI supports the ActionNameAttribute from MVC. So, let’s add [ActionName(“DefaultAction”)] to all of the original methods in the Order Controller.If you compile, run and test you will notice that all of the original actions are working again.
So, back to the Vendors and Reject actions. If you test these two actions, you will get a 405 Method Not Authorized error. If you read the Web API Action Selection documentation, you will see that it filters actions based upon the HTTP verbs the action supports and the HTTP verb of the incoming request. One way to specify what verbs the action supports is starting the action method with certain words. If the method starts with ‘Put’ it supports the PUT verb. If it starts with ‘Delete’ it supports the ‘DELETE’ verb. So that explains why the original actions starting working again once we added the ActionNameAttribute.
Let’s fix the Reject action. We add [ActionName(“Reject”)] attribute to the method and then start the method name with the word ‘Put’ and now it’s working.
The other way to specify what verbs the action supports is by adding additional attributes to the method. Adding the HttpPostAttribute indicates the method supports POST. Adding the HttpDeleteAttribute indicates the method supports DELETE. So, let’s fix the Vendors action. We simply add the [HttpGet] attribute and now that’s working.
To be clear, you can apply either technique to any of the action methods in the Controller. It’s just a matter of preference.
So there you have it. Both verb-based routing and action-based routing working in the same controller. No nuget packages. No custom controller selector and no custom action selector.
You can find the final OrderController.cs and the WebApiConfig.cs containing the required route configuration in my webapi-routing-sample project on GitHub.
No comments:
Post a Comment