.NET Web API interview questions

Basic Questions

  1. What is .NET Web API?
    • .NET Web API is a framework for building HTTP-based services that can be consumed by various clients, including browsers, mobile devices, and desktop applications.

 

  1. What are the advantages of using Web API?
    • Lightweight and suitable for devices with limited bandwidth.
    • Platform-independent and stateless communication.
    • Supports CRUD operations using HTTP methods like GET, POST, PUT, DELETE.

 

  1. What are the differences between Web API and WCF?
    • Web API: Supports only HTTP, ideal for RESTful services.
    • WCF: Supports multiple transport protocols like HTTP, TCP, and MSMQ.

 

  1. What is REST, and how does Web API implement it?
    • REST (Representational State Transfer) is an architectural style.
    • Web API implements REST by leveraging HTTP methods (GET, POST, PUT, DELETE) and supports stateless communication.

 

  1. What is the difference between GET and POST?
    • GET: Retrieves data without modifying the server's state.
    • POST: Submits data to the server and changes the server's state.

Intermediate Questions

  1. What is the difference between IActionResult and ActionResult?
    • IActionResult is an interface, while ActionResult is an implementation.
    • IActionResult allows more flexibility in returning different result types.

 

  1. How do you secure a Web API?
    • Implement authentication (JWT, OAuth).
    • Use HTTPS.
    • Apply authorization filters.
    • Use validation and parameter binding to sanitize inputs.

 

·  What is attribute routing in Web API?

  • It defines routes using attributes directly on controllers or action methods, offering more control over URIs.

Csharp

[Route("api/[controller]/[action]")]

public class SampleController : ControllerBase

 

·  What is dependency injection, and how is it implemented in Web API?

  • Dependency injection (DI) decouples dependencies from the code, improving maintainability.
  • It is implemented using services.AddScoped, AddSingleton, or AddTransient in the Startup.cs file.

 

·  What is the role of HttpResponseMessage in Web API?

  • It represents HTTP responses, allowing you to set the status code, headers, and body content.

Advanced Questions

  1. How can you handle exceptions in Web API?
    • Use global exception handling via ExceptionFilterAttribute or middleware.

Csharp

public class CustomExceptionFilter : ExceptionFilterAttribute

{

    public override void OnException(HttpActionExecutedContext context)

    {

        context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)

        {

            Content = new StringContent("An error occurred")

        };

    }

}

  1. What is CORS, and why is it important?
    • Cross-Origin Resource Sharing (CORS) is a mechanism to allow restricted resources on a web server from different origins.
    • It’s crucial for enabling secure cross-domain communication.

Csharp

services.AddCors(options => options.AddPolicy("AllowAll", builder =>

    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

  1. How do you version a Web API?
    • URL versioning: api/v1/resource.
    • Query string: api/resource?version=1.
    • Header-based versioning: Custom headers to specify versions.
  2. How do you use filters in Web API?
    • Filters are attributes used for cross-cutting concerns like logging, authentication, and error handling. Examples: AuthorizationFilter, ActionFilter.

 

  1. What is the difference between middleware and filters?
    • Middleware: Executes before the MVC pipeline starts.
    • Filters: Executes within the MVC pipeline, specific to action methods.

 

How do you test a Web API?

  • Use tools like Postman, Swagger, or Unit testing frameworks (e.g., xUnit, MSTest).

How do you implement logging in Web API?

  • Use ILogger from the Microsoft.Extensions.Logging namespace.

Csharp

private readonly ILogger<SampleController> _logger;

 

public SampleController(ILogger<SampleController> logger)

{

    _logger = logger;

}

 

[HttpGet]

public IActionResult Get()

{

    _logger.LogInformation("Fetching data...");

    return Ok("Data fetched");

}

 

What is .NET Web API?

.NET Web API is a framework by Microsoft for building HTTP-based services. It uses the HTTP protocol and RESTful principles to create APIs that can be consumed by various platforms such as web browsers, mobile devices, and other systems.

  • Key Features:
    • Built on .NET Core or .NET Framework.
    • Supports JSON and XML serialization.
    • Provides a lightweight and scalable solution for web services.

Differences Between Web API and WCF

Feature

Web API

WCF

Protocol Support

Only HTTP

HTTP, TCP, MSMQ, Named Pipes

RESTful Support

Yes

Limited

Lightweight

Yes

No

Hosting

IIS, Self-host, Kestrel

IIS, Self-host

 

Example:

  • Web API: Ideal for RESTful services (e.g., CRUD operations over HTTP).
  • WCF: Use when multiple transport protocols are required.

Attribute Routing in Detail

Attribute routing lets you define routes directly on controller actions. This provides better control over the URIs.

Example:

Csharp

[Route("api/products/{id:int}")]

public IActionResult GetProductById(int id)

{

    return Ok(new { ProductId = id });

}

  • Features:
    • Constraints: {id:int} ensures id is an integer.
    • Default Values: [Route("api/products/{id:int=1}")] sets a default value.

4. Securing Web APIs with JWT Authentication

JWT (JSON Web Token) is a popular method to secure Web APIs. It involves issuing a token to the client upon successful authentication, which is included in subsequent requests for authorization.

Example:

  1. Add authentication in Program.cs or Startup.cs:

Csharp

services.AddAuthentication(options =>

{

    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(options =>

{

    options.TokenValidationParameters = new TokenValidationParameters

    {

        ValidateIssuer = true,

        ValidateAudience = true,

        ValidateLifetime = true,

        ValidateIssuerSigningKey = true,

        ValidIssuer = "yourdomain.com",

        ValidAudience = "yourdomain.com",

        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))

    };

});

  1. Protect API endpoints:

Csharp

[Authorize]

[HttpGet]

public IActionResult SecureData()

{

    return Ok("This is secure data");

}

REST vs SOAP

Feature

REST

SOAP

Protocol

Uses HTTP

Uses HTTP, SMTP, TCP, etc.

Data Format

JSON, XML

XML only

State

Stateless

Stateful or stateless

Complexity

Simple

More complex

Performance

Faster (less overhead)

Slower due to XML and envelope usage

 

Explain routing in Web API.
Routing determines how HTTP requests are mapped to controller actions. There are two types:

1.    Attribute Routing: Uses [Route] or [HttpGet].

[Route("api/products/{id}")]

public IHttpActionResult GetProduct(int id) { }

2.    Convention-based Routing: Defined in WebApiConfig.cs.

config.Routes.MapHttpRoute(

    name: "DefaultApi",

    routeTemplate: "api/{controller}/{id}",

    defaults: new { id = RouteParameter.Optional }

)

             

How do you handle errors in Web API?
Error handling can be achieved through:

1.    Try-Catch Blocks: For local error handling.

2.    Global Exception Handling:

public static void Register(HttpConfiguration config) 

{ 

    config.Filters.Add(new CustomExceptionFilter()); 

}

3.    Exception Filters:

public class CustomExceptionFilter : ExceptionFilterAttribute 

{ 

    public override void OnException(HttpActionExecutedContext context) 

    { 

        context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError); 

    } 

}

 Create and throw exceptions

You can define your own exception by inheriting from the Exception class

Best Practices When Throwing Exceptions

  1. Use Specific Exceptions: Use specific exceptions (e.g., ArgumentNullException, InvalidOperationException) rather than the generic Exception.
  2. Provide Meaningful Messages: Include a detailed message when throwing an exception to help diagnose the issue.
  3. Don't Use Exceptions for Control Flow: Exceptions should be used to handle exceptional scenarios, not normal control flow.
  4. Include Inner Exceptions: If you rethrow an exception, include the original exception using the innerException parameter to preserve the stack trace.

Comments

Popular posts from this blog

SQL

C# operations