ASP.Net Core MVC Interview Questions


Q1. Dependency Injection in ASP.NET Core:

    - A design pattern where an object receives other objects that it needs.

public class HomeController : Controller
{
    private readonly IMyService _myService;

    public HomeController(IMyService myService)
    {
        _myService = myService;
    }
}

Q2. Service Lifecycles in ASP.NET Core:

    - Singleton: A single instance per application.

    - Scoped: A single instance per request.

    - Transient: A new instance every time it is requested.

services.AddSingleton();
services.AddScoped();
services.AddTransient();

Q3. Use of Different Service Lifecycles in ASP.NET Core:

    - Singleton: Suitable for stateless services.

    - Scoped: Suitable for services that need to maintain state within a request.

    - Transient: Suitable for lightweight, stateless services.


Q4. Kestrel Server in ASP.NET Core:

    - A cross-platform web server for ASP.NET Core applications.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup().UseKestrel();
            });
}

Q5. IIS (Internet Information Services):

    - A flexible, secure, and manageable web server for hosting web applications and services on Windows.


Q6. Difference between Web API Controller and MVC Controller:

    - Web API Controller: Designed for building HTTP services.

    - MVC Controller: Designed for building web applications that return HTML views.


Q7. Handling CORS (Cross-Origin Resource Sharing) in ASP.NET Core:

    - Configuring the application to allow or restrict cross-origin requests.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowAll");
}

Q8. Content Negotiation in ASP.NET Web API:

    - Selecting the best representation for a given response based on the client's preferences.


Q9. Return Types in ASP.NET Core:

    - Common return types include 'IActionResult', 'ActionResult', 'ViewResult', 'JsonResult', etc.

public IActionResult Index()
{
    return View();
}

Q10. Difference between 'IActionResult' and 'ActionResult' in ASP.NET Core:

    - 'IActionResult': An interface representing the result of an action method.

    - 'ActionResult': A base class for action results, providing concrete implementations.


Q11. Difference between 'IEnumerable' and 'IQueryable' in C#:

    - 'IEnumerable': Represents a collection of data that can be enumerated, executing queries in memory.

    - 'IQueryable': Represents a collection of data that can be queried remotely, executing queries on the data source.

IEnumerable numbers = new List { 1, 2, 3 };
IQueryable queryableNumbers = numbers.AsQueryable();

Q12. Model Binding in ASP.NET MVC:

    - Maps HTTP request data to action method parameters.

public ActionResult Edit(int id, [Bind(Include = "Name,Age")] Person person)
{
    // Update the person
    return View(person);
}

Q13. JWT (JSON Web Token):

    - A compact, URL-safe means of representing claims to be transferred between two parties.

var token = new JwtSecurityToken(
    issuer: "example.com",
    audience: "example.com",
    claims: claims,
    expires: DateTime.Now.AddMinutes(30),
    signingCredentials: credentials);

Q14. Claims in JWT:

    - Statements about an entity (typically the user) and additional data.

var claims = new[]
{
    new Claim(JwtRegisteredClaimNames.Sub, "user1"),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

Q15. Issuer in JWT:

    - The entity that issues the JWT, typically the authentication server.

var token = new JwtSecurityToken(
    issuer: "example.com",
    // other parameters
);

Q16. Issued To in JWT:

    - The recipient for whom the JWT is intended, typically the client application.

var token = new JwtSecurityToken(
    audience: "example.com",
    // other parameters
);

Q17. Hashing Algorithm in JWT:

    - JWTs typically use hashing algorithms like HMAC SHA256 for signing the token.

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-256-bit-secret"));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

Q18. Managing Varying Expiration Times of JWT Tokens:

    - Adjusting the token's expiration claim ('exp') and handling token renewal or refresh.

var token = new JwtSecurityToken(
    // other parameters
    expires: DateTime.Now.AddMinutes(30),
);

Q19. Identity Server in ASP.NET Core:

    - A framework for building identity and access control (IAM) solutions, supporting OpenID Connect and OAuth 2.0 protocols.


Q20. Session Management in ASP.NET Core MVC:

    - Storing user-specific data for the duration of a user's session.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();
}

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
}

Q21. Areas in ASP.NET MVC:

    - Used to organize related controllers, views, and models into separate sections within an MVC application.

public class AdminAreaRegistration : AreaRegistration
{
    public override string AreaName => "Admin";

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

Q22. UserManager in ASP.NET Identity:

    - Provides APIs for managing user-related operations.

private readonly UserManager _userManager;

public AccountController(UserManager userManager)
{
    _userManager = userManager;
}

Q23. SignInManager in ASP.NET Identity:

    - Provides APIs for managing user sign-in operations.

private readonly SignInManager _signInManager;

public AccountController(SignInManager signInManager)
{
    _signInManager = signInManager;
}

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!