1. What is .NET Core and how is it different from .NET Framework?
Answer:
.NET Core is a cross-platform, open-source framework maintained by Microsoft. Unlike the .NET Framework, which is Windows-only, .NET Core runs on Windows, Linux, and macOS. It’s optimized for modern app development like microservices and cloud-based apps.
2. What is a Web API in .NET Core?
Answer:
A Web API is a framework for building HTTP-based services that can be consumed by a broad range of clients including browsers, mobile apps, and IoT devices. In .NET Core, Web API uses the ASP.NET Core MVC framework, but it returns data instead of views.
3. How do you create a simple Web API in .NET Core?
Answer:
-
Create a new project using
dotnet new webapi
. -
Define your controller by inheriting from
ControllerBase
. -
Use routing attributes like
[HttpGet]
,[HttpPost]
, etc. -
Return data using
ActionResult<T>
.
4. What is Dependency Injection in .NET Core?
Answer:
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control. .NET Core has built-in support for DI through the IServiceCollection
interface where you can register services with AddScoped()
, AddTransient()
, or AddSingleton()
.
5. What is Middleware in ASP.NET Core?
Answer:
Middleware are components that form the request pipeline. Each middleware can handle, modify, or pass the HTTP request to the next middleware. Examples include authentication, logging, and error handling.
6. What are Filters in .NET Core Web API?
Answer:
Filters allow you to add custom processing before or after the execution of an action method. Common types include:
-
Authorization filters
-
Action filters
-
Exception filters
-
Resource filters
7. What is the difference between IActionResult and ActionResult<T>?
Answer:
-
IActionResult
is a general return type that provides flexibility. -
ActionResult<T>
combines the features ofIActionResult
and allows returning a specific model type (e.g.,ActionResult<User>
).
8. How does Routing work in ASP.NET Core Web API?
Answer:
Routing in ASP.NET Core is attribute-based by default. Example:
9. What are some best practices for building a .NET Core Web API?
Answer:
-
Use DTOs to shape data.
-
Implement versioning (e.g.,
/api/v1/products
). -
Use dependency injection wisely.
-
Handle exceptions globally.
-
Secure your API using JWT or OAuth2.
10. How do you implement Authentication and Authorization in .NET Core Web API?
Answer:
Use JWT (JSON Web Tokens) for stateless authentication:
-
Configure authentication in
Startup.cs
usingAddAuthentication()
andAddJwtBearer()
. -
Protect endpoints with
[Authorize]
.
Example:
Comments
Post a Comment