• Web API Basic Design
  • Web API - Authentication
  • Web API - JWT authentication
  • Web API - Custom Filter
  • Web API - Configuration
  • Web API vs Web Services
  • ApiController vs Controller
  • The Types of Status Codes
  • Security in Web API
  • Post File using WebAPI
  • What is Web API?
  • Is it possible to use RESTful services using WCF?
  • Why select Web API?
  • Is it right that ASP.NET Web API has replaced WCF?
  • What are the advantages of Web API?
  • What are main return types supported in Web API?
  • Web API supports which protocol?
  • Which .NET framework supports Web API?
  • Web API uses which open-source library for JSON serialization?
  • Web API sends which HTTP status code for all uncaught exception?
  • What is the biggest disadvantage of "Other Return Types" in Web API?
  • How do you construct HtmlResponseMessage?
  • What is Web API Routing?
  • What is SOAP?
  • What is the benefit of using REST in Web API?
  • How can we use Web API with ASP.NET Web Form?
  • How to you can limit Access to Web API to Specific HTTP Verb?
  • Can you use Web API with ASP.NET Web Form?
  • How Can assign alias name for ASP.NET Web API Action?
  • What is the meaning of TestApi?
  • Explain exception filters?
  • How can we register exception filter from the action?
  • How you can return View from ASP.NET Web API method?
  • How to register exception filter globally?
  • Give me one example of Web API Routing?
  • Explain what is REST and RESTFUL?
  • How can you handle errors in Web API?
  • What New Features comes with ASP.NET Web API 2.0?
  • How can you restrict access methods to specific HTTP verbs in Web API?
  • How can you pass multiple complex types in Web API?
  • Write a code for passing ArrayList in Web API?
  • Name the tools or API for developing or testing web api?
  • What is REST?
  • How to unit test Web API?
  • How can we restrict access to methods with specific HTTP verbs in Web API?
  • What is the usage of DelegatingHandler?
  • How can we register exception filter from the action?
  • code snippet to show how we can return 404 errors from HttpError?
  • Explain code snippet to register exception filters from controller?
  • Web API supports which protocol?
  • Which of the following .NET framework supports Web API?
  • Web API uses which library for JSON serialization?
  • Explain method to handle error using HttpError in Web API?
  • What is the benefit of WebAPI over WCF?
  • State differences between MVC and WebAPI
  • Who can consume WebAPI?
  • How can we make sure that Web API returns JSON data only?
  • What are the most common types of formatters used
  • What is a media type formatter in the context of Web API?
  • What is content negotiation?
  • Ensure certain members are not serialized in the response?
  • What is the use for custom message handlers?
  • How do we create a custom message handler
  • Where do we register our customer message handlers?
  • Different ways to host WebAPI
  • Need updates from the WebAPI to reach the client continously?
  • Fundamental Difference wrt hosting between ASP.Net MVC and Web API?
  • Difference in content negotiation is between ASP.Net MVC and WebAPI.
  • what is the latest version of asp.net web api
  • What HTTP verbs do the Web API CRUD operations map to?
  • Which http requests support caching?
  • What is CORS and does Web API 2.1 support CORS?
  • What is OWIN in the context of WebAPI?
  • conventional based routing vs attribute routing in web api?
  • Does Asp.Net web API support SOAP protocol?

Web API Basic Design

 

 

 

  1. Defining the Resource
  2. Verbs and Web API
  3. Content Negotiation
  4. Tools for Testing (Fiddler, PostMan)
  5. Consuming a REST API using jQuery

 

Defining the Resource

  • Defining Web API Resources
  • Collection or Singleton: /widgets or /widgets/1
  • Navigation: /widgets/1/things or /widgets/1/things/1
  • Nouns
    “Target of a hypertext reference”
  • Avoid exposing business logic, i.e. if a process requires orchestration across multiple resources, make the process the noun
  • In Web API, a resource is typically a controller

Verbs and Web API

Planning actions in your API:

  • GET – “read”
  • POST – “insert” (collection)
  • PUT – “replace”
  • DELETE – “remove”
  • PATCH – “update”
  • Custom (proceed with caution)

Content Negotiation

Tools for Testing (Fiddler, PostMan)

Consuming a REST API using jQuery

Why JSON is such a good thing :

  • $.ajax
  • Verbs (PUT, POST, GET)
  • URL (resource)
  • Data
  • DataType
  • JSON makes it really, really easy to turn into a JavaScript object

Web API - Authentication

Authorization

Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.

  • Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • Within a controller action, you can get the current principal from the ApiController.User property. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

 

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of individual actions.

Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

C#Copy

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

C#Copy

// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
    public HttpResponseMessage Get(int id) { ... }
    public HttpResponseMessage Post() { ... }
}

Action: To restrict access for specific actions, add the attribute to the action method:

C#Copy

public class ValuesController : ApiController
{
    public HttpResponseMessage Get() { ... }

    // Require authorization for a specific action.
    [Authorize]
    public HttpResponseMessage Post() { ... }
}

Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. In the following example, the Post method is restricted, but the Get method allows anonymous access.

C#Copy

[Authorize]
public class ValuesController : ApiController
{
    [AllowAnonymous]
    public HttpResponseMessage Get() { ... }

    public HttpResponseMessage Post() { ... }
}

In the previous examples, the filter allows any authenticated user to access the restricted methods; only anonymous users are kept out. You can also limit access to specific users or to users in specific roles:

C#Copy

// Restrict by user:
[Authorize(Users="Alice,Bob")]
public class ValuesController : ApiController
{
}
   
// Restrict by role:
[Authorize(Roles="Administrators")]
public class ValuesController : ApiController
{
}

Custom Authorization Filters

To write a custom authorization filter, derive from one of these types:

  • AuthorizeAttribute. Extend this class to perform authorization logic based on the current user and the user's roles.
  • AuthorizationFilterAttribute. Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role.
  • IAuthorizationFilter. Implement this interface to perform asynchronous authorization logic; for example, if your authorization logic makes asynchronous I/O or network calls. (If your authorization logic is CPU-bound, it is simpler to derive from AuthorizationFilterAttribute, because then you don't need to write an asynchronous method.)

The following diagram shows the class hierarchy for the AuthorizeAttribute class.

Authorization Inside a Controller Action

In some cases, you might allow a request to proceed, but change the behavior based on the principal. For example, the information that you return might change depending on the user's role. Within a controller method, you can get the current principal from the ApiController.User property.

C#Copy

public HttpResponseMessage Get()
{
    if (User.IsInRole("Administrators"))
    {
        // ...
    }
}


Web API - Custom Filter

One approach would be a custom ActionFilter. See here, although it's about MVC the concept is identical to WebAPI:

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

For example:

    public class MyActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
           //....
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
           //....
        }
    }

And use that do decorate your API controllers/actions:

    [MyActionFilter]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

Web API - Configuration

 

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                  name: "titleAll",
                  pattern: "{controller=Files}/{action=Show}/{title}");
                endpoints.MapControllerRoute(
                  name: "slug",
                  pattern: "{controller=Services}/{action=Show}/{slug?}");
                endpoints.MapControllerRoute(
                   name: "titleWithSearch",
                   pattern: "{controller=Files}/{action=Show}/{slug?}/{s?}");
                endpoints.MapRazorPages();
            });


            app.Run(async context =>
            {
                // Setting DefaultAuthenticateScheme causes User to be set
                var user = context.User;

                // Deny anonymous request beyond this point.
                if (user == null || !user.Identities.Any(identity => identity.IsAuthenticated))
                {
                    await context.ChallengeAsync();

                    return;
                }

                // Display user information
                var response = context.Response;
                response.ContentType = "text/html";
                await response.WriteAsync("<html><body>");
                await response.WriteAsync("Hello " + (context.User.Identity.Name ?? "anonymous") + "<br>");
                foreach (var claim in context.User.Claims)
                {
                    await response.WriteAsync(claim.Type + ": " + claim.Value + "<br>");
                }

                await response.WriteAsync("Tokens:<br>");

                await response.WriteAsync("Access Token: " + await context.GetTokenAsync("access_token") + "<br>");
                await response.WriteAsync("Refresh Token: " + await context.GetTokenAsync("refresh_token") + "<br>");
                await response.WriteAsync("Token Type: " + await context.GetTokenAsync("token_type") + "<br>");
                await response.WriteAsync("expires_at: " + await context.GetTokenAsync("expires_at") + "<br>");
                await response.WriteAsync("<a href=\"/logout\">Logout</a><br>");
                await response.WriteAsync("<a href=\"/refresh_token\">Refresh Token</a><br>");
                await response.WriteAsync("</body></html>");
            });


Web API vs Web Services

Difference between Web Services and Web APIs:

WEB SERVICES WEB API
Web services are a type of API, which must be accessed through a network connection. APIs are application interfaces, implying that one application can communicate with another application in a standardized manner.
Web service is used for REST, SOAP and XML-RPC for communication. API is used for any style of communication.
All Web services are APIs. APIs are not web services.
It doesn’t have lightweight design, needs a SOAP convention to send or receive data over the system. It has a light-weight architecture furthermore, useful for gadgets which have constrained transmission capacity like smart phones.
It provides supports only for the HTTP protocol. It provides support for the HTTP/s protocol: URL Request/Response Headers, and so on.
It is not open source, however, can be devoured by any customer that comprehends xml. It is an open source and also ships with .NET framework.
Web service supports only XML. API supports XML and JSON.
Web Services can be hosted on IIS. Web API can be hosted only on IIS and self.

ApiController vs Controller

Difference between Web Services and Web APIs:

  Controller WEB API Controller
assembly "System.Web.Mvc" "System.Web.Http"
   

The Web API helps the creation of RESTful services over the .Net Framework but the MVC does not support.

Return

Use Controller to render your normal views.

We can use the MVC for developing  the Web application that replies as both data and views

ApiController action only return data that is serialized and sent to the client.

Web API is used for generating the HTTP services that replies only as data.

ReturnType MVC returns the data in the JSON format by using JSONResult.

.Web API controllers do not return views, they return data.

The Web API returns the data in various formats, such as JSON, XML and other format based on the accept header of the request.

When to use if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning JSON here and there - stick with MVC/Controller. If you want to provide a data-driven/REST-ful interface to a system, go with WebAPI.
content negotiation, self-hosting content negotiation, self-hosting are not supported by the MVC.

The Web API supports content negotiation, self hosting.

     

The Types of Status Codes

 

  • 1XX Codes: Informational codes. Rarely used in modern web apps.
  • 2XX Codes: Success codes. Tells the client that the request succeeded.
  • 3XX Codes: Redirect codes. Tells the client that they may need to redirect to another location.
  • 4XX Codes: Client Error codes. ...
  • 5XX Codes: Server Error codes.