How to Get Browser Agent from ASP.NET Web API Controller? | ASP.NET Web API Tutorial

The easiest way to get the full user-agent from inside an ASP.NET Web API-controller is as given below:
var userAgent = Request.Headers.UserAgent.ToString();
It gives exactly the same result as doing the manual step like this:
// var headers = request.Headers.GetValues("User-Agent");
// var userAgent = string.Join(" ", headers);

What is HATEOAS, REST, and Hypermedia? | ASP.NET MVC, ASP.NET Web API, Azure Video Tutorial

, , ,
Scott Hanselman and Mat Velloso talks about REST and RESTful Web Services. Also discusses about HATEOAS, which actually means "Hypermedia as the Engine of Application State." Scott talks to Mat Velloso about all these topics and get s a nice primer on REST as it relates to hosting Web Services in the Azure Cloud.

What is Mean by Cross-Origins and Same-Origins? | HTTP Interview Question

, ,


Two URLs have the same origin if they have identical schemes, hosts, and ports. (RFC 6454)
These two URLs have the same origin:
  • http://example.com/foo.html
  • http://example.com/bar.html
These URLs have different origins than the previous two:
  • http://example.net - Different domain
  • http://example.com:9000/foo.html - Different port
  • https://example.com/foo.html - Different scheme
  • http://www.example.com/foo.html - Different subdomain
Internet Explorer does not consider the port when comparing origins.

Enabling CORS in ASP.NET Web API | ASP.NET Web API Programmer Guide | ASP.NET Web API Tutorial

As given in the wikepedia, 'Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests'.

We need a NuGet package Microsoft.AspNet.WebApi.Cors to enable CORS in Web API. So let us first add the CORS NuGet package. In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Cors
This command installs the latest package and updates all dependencies, including the core Web API libraries. User the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
Next, add the [EnableCors] attribute to the ValuesController class:
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ValuesController : ApiController
    {
        // Controller methods not shown...
    }
}
For the origins parameter, use the URI where you deployed the WebClient application or simply put "*" if you would like to support any webclient. This allows cross-origin requests from WebClient, while still disallowing all other cross-domain requests. Later, I’ll describe the parameters for[EnableCors] in more detail.

Redeploy the updated Web API application. You don't need to update WebClient. Now the AJAX request from WebClient should succeed. The GET, PUT, and POST methods are all allowed.

Creating ASP.Net Web API REST Services | ASP.Net Web API Video Tutorial | ASP.Net Web API REST Programmer Guide

,
In this Asp.Net Web API video tutorial presented by Brock Allen for DevelopMentor, we will take a look at these benefits of Web API REST services and how to get started building HTTP-based (REST) services using the ASP.NET Web API framework. We will explore how HTTP-based (REST) services use standard HTTP constructs like resources URLs, methods and status codes and how Web API as a framework supports these programming constructs.

How to avoid Sending Stack Trace of Unhandled Exception in ASP.NET Web API? | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
When an exception is thrown and it is not handled, ASP.NET Web API returns a 500 Internal Server Error. This response will have the stack trace details in the response body. However, sending a stack trace is a security risk.

ASP.NET Web API Stack Trace of unhandled exceptions can be avoided by specifying the Never option for the error details inclusion policy in WebApiConfig.cs under the App_Start folder, the stack trace can be stopped from getting to the client.

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

Explain HTTP Request? | ASP.Net Web API Interview Question | ASP.Net Web API Programmer Guide | HTTP Programmer Guide

,
An HTTP request has the request line as the first line of the request. The request line starts with the HTTP method followed by a space, followed by the URI of the resource requested, a space, and then the HTTP version. The request line is terminated by a Carriage Return (CR) and a Line Feed (LF) character, as shown in below figure:



Following the request line are the request headers. The header fields are colon-separated key–value pairs, terminated by a CRLF, just like the request line. The end of the header fields is indicated by an empty field—two consecutive CRLF pairs—as shown in below figure:

 Finally, following the request headers is the optional request body. Depending on the HTTP method used, the request body can be present or absent.

Manipulating Resources Through Representations in ASP.NET Web API | ASP.NET Web API Programmer Guide

The example of a user typing http://server/api/employees/12345 in Internet Explorer can be described as a user requesting a resource using the GET verb and getting back the employee JSON, which is the representation of the resource. GET is guaranteed not to cause any side effect and is said to be nullipotent; nothing happens to the system’s state, even when called multiple times or not called at all. In other words, the system state will be the same for all the following scenarios: (1) method was not called at all, (2) method was called once, and (3) method was called multiple times.

Other important verbs are POST, PUT, and DELETE. POST is for creating a new resource, PUT is for updating an existing resource, and DELETE is for deleting an existing resource. PUT and DELETE are idempotent; the effect to the system state will be the same as that of the first call, even when called multiple times subsequent to the first call.

To create a new employee, the client sends a POST request, with the new employee (JSON or XML representation) in the body of the request. This request gets mapped to a method with a name starting with Post, which is Post(Employee) in this case.

Updating an employee is the same as creating a new employee except that the PUT verb is used and mapping is based on the name starting with Put. One important difference compared to POST is that PUT is idempotent. If a user sends multiple requests to update an employee to the same state, no error must be sent back.

Deleting an employee is similar except that a resource representation is not needed. A DELETE request against the URI will be sufficient to delete the resource. Similar to PUT, the DELETE method is also idempotent. Even if the underlying data source sends an error back when the employee to be deleted no longer exists, because it is already deleted in response to the previous request, no error must be sent back.

In the below code snippet for example of how ASP.NET Web API supports manipulation of resources through different action methods.
public class EmployeesController : ApiController
    {
        public Employee Post(Employee human)
        {
            // Add employee to the system
        }
        public void Delete(int id)
        {
            // Delete employee from the system  
        }
        public void Put(Employee employee)
        {
            // Update employee in the system  
        }
    }

ActionResource IdentifierVerbRequest BodyResponse Body
List of all employees http://server/ api/employees GET None JSON/XML, representation of the resource requested, which is the list of employees
Get a specific employee http:// server/api/ employees/12345 GET None JSON/XML, representation of the resource requested, which is the specific employee
Create a new employee http://server/ api/employees POST JSON/XML representation of the resource getting added, which is the new employee JSON/XML, representation of the resource, which is the new employee that just got added into the system. The difference between this representation and the one in the request body could be that the employee ID that got generated by the system could be present in the response representation
Update an existing employee http:// server/api/ employees/12345 PUT JSON/XML representation of the resource getting updated None
Delete an existing employee http:// server/api/ employees/12345 DELETE None None

For all the preceding actions, a status code is the means through which the status of the action is communicated back. By default it is 200 – OK, indicating success. As a special case, 201 – Created gets sent for POST, when a resource was created. 401 – Not authorized gets sent when a user requests an action on a resource that requires the user to be authenticated and that user has either not provided the credentials or provided invalid credentials. 404 – Not Found gets sent when the user has requested an action on a resource that does not exist. There are multiple other status codes.

Identifying Resources in ASP.NET Web API | ASP.NET Web AP| Programmer Guide | ASP.NET Web API Tutorial

In previous articles, we have discussed about what is RESTful service and the constraints involved and how to resolve these constraints of REST in ASP.Net Web API. Now let us see how to identify a resource in ASP.Net Web API?.

A resource is any data that a web API sends to its clients. Examples could be a product that your company sells, a purchase order received from a buyer, a list of employees in your company, or an individual employee in a department. In the real world, a product or an employee could be uniquely identified through an identifier, such as a product ID or an employee ID.

In the case of RESTful web services, a resource is identified by a URI. An employee with an identifier of 12345 will be represented by http://server/employees/12345. In the case of ASP.NET Web API, the URI can be slightly different and it includes api by default in the URI, so it will be more like http://server/api/employees/12345. If you fire up an instance of Internet Explorer, type that URI in the address bar, and press Enter, Internet Explorer does an HTTP GET and you will get the JSON representation of the resource, which is an employee with the ID of 12345 in this case.

From the .NET code point of view (see code below), the corresponding class will be EmployeesController, which is a subclass of ApiController and the method that executes to create the resource representation to be sent back to the client in its Get(int) method.

public class EmployeesController : ApiController
    {
        public Employee Get(int id)
        {
            // return employee      
        }
        public IEnumerable<Employee> GetAllEmployees()
        {
            // return all employees  
        }
    }
In the above code, the resource that is a noun has the URI representation of http://server/api/employees/12345. This resource was accessed through GET HTTP method, which is the verb. Like one single employee, a list of employees is also a resource and its identifier will be http://server/api/employees. The corresponding method is GetAllEmployees(), which returns IEnumerable<Employee>.

How to Build a Service that Satisfies RESTful constraints using the ASP.NET Web API framework? | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
In my previous article, I have explained about the what is RESTful service and the constraints involved. Now let us see how the ASP.Net Web API satisfies those constraints.

Client-server constraint is an easy one to satisfy out of the box. ASP.NET Web API is all about responding to the client request with the data, without bothering about client state or how data will be presented to the end user.

Stateless constraint can also be easily satisfied out of the box, unless something horrible is done such as using the ASP.NET session state from the web API. ASP.NET MVC supports the OutputCache attribute that can be used to control output caching. ASP.NET Web API has no support out of the box, but it is easy to roll out our own action filter attribute. The bottom line is that the Cache-Control response header is the lever ASP.NET Web API can use to label a response as cacheable or not. By default, Cache-Control is set to no-cache and the response is not cached.

Layered constraint is more along the infrastructure line—proxies, firewalls, and so on. There is nothing special that needs to be done from ASP.NET Web API to satisfy this constraint.

Uniform interface constraint includes the following four constraints and is a key factor in deciding if an HTTP service is RESTful or not.

  1. Identification of resources
  2. Manipulation of resources through representations
  3. Self-descriptive messages
  4. Hypermedia as the engine of application state (HATEOAS) 

What Is a RESTful Service? | ASP.NET Web API Interview Question | RESTful Service Programmer Guide

,
Representational State Transfer (REST) is an architectural style. The term REST was introduced and defined by Roy T. Fielding in his doctoral dissertation in the year 2000. A service that conforms to the REST constraints is referred to as being RESTful. To be RESTful, a service has to conform to the following mandatory constraints.

  1. Client-server constraint, which is based on the separation of concerns, is about separating user interface concerns from data storage concerns. Clients are not concerned with data storage, which is a concern of servers, and servers are not concerned with the user interface or user state, which are concerns of clients.
  2. Stateless constraint is about each request being an independent self-contained unit with all the necessary information for the server to service the request without looking at anything else for the context.
  3. Cache constraint is about the server being able to label a response as cacheable or not,  so that the client handles the response appropriately from the point of view of later use.
  4. Layered constraint is about composing the system into layers, with each layer being  able to see and interact with only its immediate neighbor. A layer cannot see through  its neighbor. Between the client and server, there could be any number of  intermediaries—caches, tunnels, proxies, and so on.
  5. Uniform interface constraint is about providing a uniform interface for identification of resources, manipulation of resources through representations, self-descriptive messages, and hypermedia as the engine of application state.

Scenarios to Choose ASP.NET Web API | Scenarios Implementing ASP.NET Web API | ASP.NET Web API Programmer Guide

Let us see some of the scenarios where ASP.NET Web API can add value to an application or system architecture.  The following are the scenarios where ASP.NET Web API, as the back end, brings the most value to the system.


  • Rich client web applications: ASP.NET Web API will be a good fit for rich client web applications that heavily use AJAX to get to a business or data tier. Client applications  can be anything capable of understanding HTTP. It can be a Silverlight application or an Adobe Flash–based application or a single-page application (SPA) built using JavaScript libraries such as JQuery, Knockout, and so on, to leverage the power of JavaScript and HTML5 features.
  • Native mobile and nonmobile applications: ASP.NET Web API can be a back end for native applications running on mobile devices where SOAP is not supported. Because HTTP is a common denominator in all the platforms, even the native applications can use a .NET back-end application through the service façade of a web API. This is especially useful when a mobile application is a secondary user interface (UI) channel with an ASP.NET MVC application being the primary UI channel. Also, native applications running on platforms other than Windows such as a Cocoa app running on Mac can use ASP.NET Web API as the back end.
  • Platform for Internet of Things (IOT): IOT devices with Ethernet controllers or a Global System for Mobile Communications (GSM) modem, for example, can speak to ASP.NET Web API services through HTTP. A platform built on .NET can receive the data and do business. Not just IOT devices, but other HTTP-capable devices such as radio frequency ID (RFID) readers can communicate with ASP.NET Web API.


Why Web API? | A Journey from Web Services (ASMX) to WCF to ASP.Net WebAPI | History of Internet Protocol | Origin of Internet

,
It all started with the launch of Sputnik in 1957, by the Union of Soviet Socialist Republics (USSR). The United States, under the leadership of then President Eisenhower, started the Advanced Research Projects Agency (ARPA) to advance the United States in the technology race, in the light of the Sputnik launch. One of the ARPA-funded projects was ARPANET, the world’s first operational packet switching network. ARPANET led to the development of protocols that allowed networks to be joined together into a network of networks that evolved into the ubiquitous Internet of today.

The terms Internet and World Wide Web or simply Web, are generally used interchangeably, but they are separate although related things. The Internet is the infrastructure on which the World Wide Web has been built. The Internet connects islands of smaller and bigger networks into one huge network. 

The World Wide Web builds on this network by providing a model to share data or information with the computer users who are all part of the Internet. Servers or web servers serve data in the form of documents or web pages to the clients, called web browsers, which display the documents in a format readable by human beings. Typically, a web page is created in a language called Hyper Text Markup Language (HTML) and is served to a browser by the web server as a result of both parties following a protocol, Hyper Text Transfer Protocol (HTTP). The Web is just one of the ways information can be shared over the Internet. Just like HTTP, there is Simple Mail Transfer Protocol (SMTP) for e-mail, File Transfer Protocol (FTP) for transfer of information in the form of files, and so on. 

Initially, web pages were just static pages existing in the file system of some computer with data that hardly changed. As the World Wide Web started to grow and the user base started to expand, there was a need for web pages to be generated on the fly. Web servers started delegating this responsibility to engines such as the Common Gateway Interface (CGI) to generate web pages on the fly. The dynamic web pages and the introduction of the client-side JavaScript scripting language led to a new generation of software applications called web applications. The end user of a web application is a human being with an objective of performing a task.

Because the end user of a web application is a human being, there is a user interface associated with a web application. The browser is what provides this interactive interface for a user. In addition, there is a need for nonhuman entities such as a machine running some software to communicate and exchange data over the World Wide Web. Enter the web service. Although not mandated, a web service uses HTTP to exchange data. Unlike a web application, which is mainly about HTML over HTTP, for a web service it is mainly Extensible Markup Language (XML) over HTTP. A client sends a request in XML, and the server responds with an XML response. This XML can be Plain Old XML (POX), which is typically a nonstandard XML only the client and server will be able to make sense out of, or it can be standard Simple Object Access Protocol (SOAP). 

To appreciate the value SOAP brings to the table, let us pretend we got some XML response representing an employer in an organization, as shown in below response XML:

<employee>         <firstname>John</firstname>         <lasttname>Human</lastname>         <salary>2000</salary>         <doj>06/01/1998<doj>         <lastlogin>10/20/2012 09:30:00</lastlogin>
</employee>

To do anything useful with this in our application, this XML might need to be loaded into some data structure, say an object as defined by a class in the case of an object-oriented programming (OOP) language. If I’m programming, how will I define the data type of the field to store salary? Will it be an integer or a fractional number? What if my request to get the employee fails because there is no such employee or there is some other problem? How will I know where to look in the XML if the request has failed? SOAP helps us with questions like these by providing a basic messaging framework on which web services can be built. SOAP has Microsoft roots, although it is currently maintained by the World Wide Web Consortium (W3C).

Microsoft technologies such as the ASMX-based web service, which is currently a legacy technology, and its successor Windows Communication Foundation (WCF) all have great affinity toward SOAP. An ASMX-based web service allows the exchange of SOAP messages over HTTP and that’s pretty much it. WCF builds on this and tries to abstract away the infrastructure from the programming. If I have an Employee service that returns the details of an employee, I can host the service to be consumed over HTTP, over Transmission Control Protocol (TCP), through Microsoft Message Queuing (MSMQ), or any combinations thereof. By having the same contract with the client, I can have multiple binding for multiple ways my service can be reached. In both cases, though, the payload will be SOAP, by default. An important aspect of SOAP-based web services is the availability of a Web Service Definition Language (WSDL) file, which allows tooling to be built that helps in consumption of services. For example, Microsoft Visual Studio can generate proxy classes reading WSDL definitions, and the client trying to consume the services (i.e., the programmer writing the client code) can directly work with the generated classes, with the whole existence of the web service hidden from the programmer.

A web API is a service. Technically, there is no difference. What is different is the manner in which a web API is intended to be used. Let’s say I have a web application where a user can post his thoughts in the form of a short message. A user can log in to my application from a browser, add new posts or update the ones she posted in the recent past, or even delete the old ones. In other words, users can perform create, read, update, and delete (CRUD) operations on their posts using my web application. My application became so popular that there are folks who want to integrate this CRUD functionality into their mobile apps so that users can perform CRUD operations from their mobile devices without logging on to my web application while they are away from their normal computers.

I can now create a web service to support the CRUD operations. Technically it is a web service, but it is an application programming interface (API) to interact with my web application, except that it is over the Web. Traditionally, APIs are a bunch of classes with properties and methods that are part of a reusable component to interact with another application. This scenario is exactly that, except that my API is not available in the form of a software component, but over the Web instead. It is a web API.

Although it is fundamentally a web service, the intention is to use it to manipulate application data, and that is what makes it an API. One important characteristic of most of the typical web APIs in use, although not a defining characteristic, is that web APIs tend to be RESTful web services as compared with SOAP-based web services. A web service can very well be REST based, so this is not the defining characteristic. By using REST, a web API tends to be lightweight and embraces HTTP. For example, a web API leverages HTTP methods to present the actions a user would like to perform and the application entities would become resources these HTTP methods can act on. Although SOAP is not used, messages—requests and responses—are either in XML or JavaScript Object Notation (JSON).

Types of Web API Action Return Types | Return Types in Web API Action | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
Web API supports three types of possible action return values (well, four, if you count void):
  • – HttpResponseMessage
  • – IHttpActionResult
  • – any other type, subject to content negotiation

Implementing Custom Message Handlers In ASP.NET Web API | ASP.NET Web API Reference Guide | ASP.NET Web API Tutorial

Steps to write a custom message handler: derive from System.Net.Http.DelegatingHandler and override theSendAsync method. This method has the following signature:
Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken);
The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
  1. Process the request message.
  2. Call base.SendAsync to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response and return it to the caller.
Here is a trivial example:
public class MessageHandler1 : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("Process request");
        // Call the inner handler.
        var response = await base.SendAsync(request, cancellationToken);
        Debug.WriteLine("Process response");
        return response;
    }
}

Scenarios To Implement Custom Message Handlers in ASP.NET Web API | ASP.NET Web API Reference Guide | ASP.NET Web API Tutorial

Adding custom handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:
  • Read or modify request headers.
  • Add a response header to responses.
  • Validate requests before they reach the controller.

Explain Server-Side Message Handlers In ASP.NET Web API? | ASP.NET Web API Interview Question

,
On the server side, the Web API pipeline uses some built-in message handlers:
  • HttpServer gets the request from the host.
  • HttpRoutingDispatcher dispatches the request based on the route.
  • HttpControllerDispatcher sends the request to a Web API controller.
You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:
  • Read or modify request headers.
  • Add a response header to responses.
  • Validate requests before they reach the controller.
This diagram shows two custom handlers inserted into the pipeline:

Explain Delegating Handlers? | Web API Interview Question | .Net Interview Question

,
Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.

Knockout.js Role In ASP.NET MVC Application | Knockout.js Tutorial | ASP.NET MVC Tutorial | ASP.NET Web API Tutorial

, ,
Knockout.js is a Javascript library that makes it easy to bind HTML controls to data. Knockout.js uses the Model-View-ViewModel (MVVM) pattern.
  • The model is the server-side representation of the data in the business domain (in our case, products and orders).
  • The view is the presentation layer (HTML).
  • The view-model is a Javascript object that holds the model data. The view-model is a code abstraction of the UI. It has no knowledge of the HTML representation. Instead, it represents abstract features of the view, such as "a list of items".
The view is data-bound to the view-model. Updates to the view-model are automatically reflected in the view. The view-model also gets events from the view, such as button clicks, and performs operations on the model, such as creating an order.