0% found this document useful (0 votes)
5 views40 pages

ASP.NET Core Web API questions

ASP.NET Core Web API is a framework for building cross-platform HTTP services, differing from traditional ASP.NET MVC by being modular and supporting both MVC and Web API in a unified framework. It facilitates building RESTful services through standard HTTP methods, routing, content negotiation, and model binding. Key features include dependency injection, CORS configuration, authentication with JWT, and various testing approaches such as unit, integration, and end-to-end testing.

Uploaded by

shivamlavekar10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views40 pages

ASP.NET Core Web API questions

ASP.NET Core Web API is a framework for building cross-platform HTTP services, differing from traditional ASP.NET MVC by being modular and supporting both MVC and Web API in a unified framework. It facilitates building RESTful services through standard HTTP methods, routing, content negotiation, and model binding. Key features include dependency injection, CORS configuration, authentication with JWT, and various testing approaches such as unit, integration, and end-to-end testing.

Uploaded by

shivamlavekar10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

ASP.

NET Core Web API

WEB API Questions


1. What is ASP.NET Core Web API, and how does it differ from traditional ASP.NET
MVC?

ASP.NET Core Web API is a framework for building HTTP services that can be accessed from various
clients, such as browsers and mobile devices. It differs from traditional ASP.NET MVC in several ways:

ASP.NET Core is cross-platform and can run on Windows, macOS, and Linux, whereas traditional
ASP.NET MVC runs only on Windows.
ASP.NET Core has a unified MVC and Web API framework, meaning the same controllers can
return both views and data.
ASP.NET Core is more modular, lightweight, and performant compared to traditional ASP.NET
MVC.
ASP.NET Core introduces new concepts such as middleware for request processing and
dependency injection as a first-class citizen.

2. Explain the concept of RESTful API and how ASP.NET Core Web API facilitates
building RESTful services.

RESTful API is an architectural style that uses HTTP requests to perform CRUD (Create, Read, Update,
Delete) operations on resources. It relies on standard HTTP methods, status codes, and URIs to access
and manipulate resources. ASP.NET Core Web API facilitates building RESTful services by:

Supporting all standard HTTP methods (GET, POST, PUT, DELETE, etc.).
Providing a routing mechanism to map URLs to specific controllers and actions.
Allowing for content negotiation to return different formats (JSON, XML, etc.) based on client
preferences.
Enabling model binding and validation to automatically bind and validate request data.

3. What are the different HTTP methods (verbs) supported by ASP.NET Core Web
API, and what are their purposes?

ASP.NET Core Web API supports the following HTTP methods:

GET: Retrieve data from the server.


POST: Submit data to be processed to the server.
PUT: Update existing data on the server.
DELETE: Remove data from the server.
PATCH: Partially update existing data on the server.
HEAD: Retrieve the headers of a resource.
OPTIONS: Retrieve the supported HTTP methods for a resource.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/40
4. Describe the use of Model Binding in ASP.NET Core Web API for parameter
binding and validation.

Model Binding in ASP.NET Core Web API is the process of extracting data from HTTP requests and
mapping it to action method parameters. It supports binding from various sources like route data,
query strings, form data, and request bodies. Validation is performed using data annotations on the
model properties. The `[FromQuery]`, `[FromBody]`, `[FromRoute]`, and `[FromForm]` attributes are used
to specify the source of data binding.

5. How do you handle routing in ASP.NET Core Web API? Explain attribute routing
and convention-based routing.

Routing in ASP.NET Core Web API is the process of mapping incoming HTTP requests to controller
actions. There are two types of routing:

Attribute Routing: Uses attributes on controller actions to define routes. Example:

csharp

[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProduct(int id) { ... }
}

Convention-based Routing: Defines routes in the `Startup.cs` file using route templates.
Example:

csharp

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller=Home}/{action=Index}/{id?}");
});

6. What is content negotiation in ASP.NET Core Web API? How do you return
different types of content based on client requests?

Content negotiation is the process of selecting the appropriate media type (e.g., JSON, XML) to return
based on the client's request. ASP.NET Core Web API uses the `Accept` header in the request to
determine the desired format. You can configure content negotiation by adding formatters in the
`Startup.cs` file:

csharp

services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/40
})
.AddXmlSerializerFormatters(); // Add XML formatter

7. Explain the use of ActionResult<T> in ASP.NET Core Web API for returning data
along with HTTP status codes.

`ActionResult<T>` is a return type that allows you to return a specific type (T) or an HTTP status code.
It provides a way to return data along with HTTP status codes, making the code more expressive and
readable. Example:

csharp

public ActionResult<Product> GetProduct(int id)


{
var product = _repository.GetProduct(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}

8. What are filters in ASP.NET Core Web API, and how do you use them for cross-
cutting concerns like logging, validation, and authorization?

Filters in ASP.NET Core Web API are used to run code before or after specific stages in the request
processing pipeline. They are useful for cross-cutting concerns like logging, validation, and
authorization. Types of filters include:

Authorization filters: Run before the controller action to authorize requests.


Resource filters: Run after authorization but before model binding.
Action filters: Run before and after the controller action.
Exception filters: Handle exceptions thrown by controller actions.
Result filters: Run before and after the action result is executed.
You can apply filters globally, at the controller level, or at the action level using attributes or by
configuring them in the `Startup.cs` file.

9. How do you handle exception handling in ASP.NET Core Web API? Describe the
use of middleware and exception filters.

Exception handling in ASP.NET Core Web API can be done using middleware and exception filters:

Middleware: You can create custom middleware to handle exceptions globally. Example:

csharp

app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var error = new { message = "An unexpected error occurred." };
await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/40
});
});

Exception Filters: You can create custom exception filters to handle exceptions at the action or
controller level. Example:

csharp

public class CustomExceptionFilter : IExceptionFilter


{
public void OnException(ExceptionContext context)
{
context.Result = new JsonResult(new { message = context.Exception.Message })
{
StatusCode = 500
};
}
}

10. Describe the concept of versioning in ASP.NET Core Web API. How do you
implement API versioning to support backward compatibility?

API versioning allows you to manage changes to your API without breaking existing clients. ASP.NET
Core Web API supports versioning through various strategies, such as URL versioning, query string
versioning, and header versioning. You can use the `Microsoft.AspNetCore.Mvc.Versioning` package to
implement versioning. Example:

csharp

services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
});

In the controller, specify the version:

csharp

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase
{
// Actions
}

11. Explain the use of dependency injection (DI) in ASP.NET Core Web API. How do
you register and use services using DI?

Dependency Injection (DI) is a technique for achieving Inversion of Control (IoC) between classes and
their dependencies. ASP.NET Core provides built-in support for DI, allowing you to register services in

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/40
the `Startup.cs` file and inject them into controllers. Example:

csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddTransient<IMyService, MyService>();
services.AddScoped<IOtherService, OtherService>();
services.AddSingleton<ISingletonService, SingletonService>();
services.AddControllers();
}

In the controller, inject the service through the constructor:

csharp

public class ProductsController : ControllerBase


{
private readonly IMyService _myService;

public ProductsController(IMyService myService)


{
_myService = myService;
}

// Actions
}

12. What is CORS (Cross-Origin Resource Sharing), and how do you configure CORS
policies in ASP.NET Core Web API to allow or restrict access from different
domains?

CORS is a security feature that allows or restricts web applications running on different domains to
access resources on your server. In ASP.NET Core Web API, you can configure CORS policies in the
`Startup.cs` file:

csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddControllers();
}

In the `Configure` method, use the CORS policy:

csharp

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/40
app.UseCors("AllowSpecificOrigin");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

13. How do you implement authentication and authorization in ASP.NET Core Web
API? Describe the use of JWT (JSON Web Tokens) and OAuth2.

Authentication and authorization in ASP.NET Core Web API can be implemented using JWT and
OAuth2. JWT is a compact, URL-safe token format that is used for securely transmitting information
between parties. OAuth2 is an authorization framework. Example of implementing JWT:

Install the `Microsoft.AspNetCore.Authentication.JwtBearer` package.


Configure JWT authentication in `Startup.cs`:

csharp

public void ConfigureServices(IServiceCollection services)


{
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("your_secret_key"))
};
});

services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Apply the `[Authorize]` attribute to controllers or actions:

csharp

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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/40
public class SecureController : ControllerBase
{
// Actions
}

14. What are the different ways of testing ASP.NET Core Web API? Describe unit
testing, integration testing, and end-to-end testing approaches.

Testing ASP.NET Core Web API involves several approaches:

Unit Testing: Focuses on testing individual components in isolation using mocking frameworks
like Moq. Example:

csharp

[Fact]
public void GetProduct_ReturnsProduct()
{
var mockRepo = new Mock<IProductRepository>();
mockRepo.Setup(repo => repo.GetProduct(1)).Returns(new Product { Id = 1, Name =
"Test" });

var controller = new ProductsController(mockRepo.Object);


var result = controller.GetProduct(1);

Assert.IsType<OkObjectResult>(result.Result);
}

Integration Testing: Tests the interaction between components and the overall behavior of the
application using `TestServer`. Example:

csharp

public class IntegrationTests


{
private readonly HttpClient _client;

public IntegrationTests()
{
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
_client = server.CreateClient();
}

[Fact]
public async Task GetProduct_ReturnsProduct()
{
var response = await _client.GetAsync("/api/products/1");
response.EnsureSuccessStatusCode();
var product = await response.Content.ReadAsAsync<Product>();
Assert.Equal(1, product.Id);
}
}

End-to-End Testing: Tests the entire application flow from start to finish using tools like
Selenium or Postman. These tests simulate user interactions and validate the application's
functionality. Example with Postman:
Create test cases in Postman.
Use Newman to run the tests in a CI/CD pipeline.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/40
C# Questions
1. What is the difference between == and Equals() in C#?

The `==` operator checks for reference equality or value equality depending on the data types. For
reference types, `==` checks if both objects reference the same memory location. For value types, it
checks if the values are equal. The `Equals()` method, on the other hand, is used to check for value
equality and can be overridden to provide custom equality comparison logic.
Example:

csharp

string str1 = "hello";


string str2 = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
Console.WriteLine(str1 == str2); // True
Console.WriteLine(str1.Equals(str2)); // True

object obj1 = new object();


object obj2 = new object();
Console.WriteLine(obj1 == obj2); // False
Console.WriteLine(obj1.Equals(obj2)); // False

2. What are the main differences between a class and a struct in C#?

Classes:
Are reference types.
Stored on the heap.
Support inheritance.
Can have destructors.
Structs:
Are value types.
Stored on the stack.
Do not support inheritance.
Cannot have destructors.

Example:

csharp

public class MyClass


{
public int Value { get; set; }
}

public struct MyStruct


{
public int Value { get; set; }
}

MyClass class1 = new MyClass();


MyStruct struct1 = new MyStruct();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/40
3. Can you explain what a namespace is and how it is used in C#?

A namespace is a way to organize code and prevent name collisions by grouping related classes,
interfaces, enums, and other types. It is declared using the `namespace` keyword and can contain
nested namespaces.
Example:

csharp

namespace MyApplication.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
}

namespace MyApplication.Services
{
public class ProductService
{
public void SaveProduct(Product product) { ... }
}
}

4. What is the purpose of the using statement in C#?

The `using` statement has two main purposes:

1. Namespace Inclusion: It allows access to classes and types defined in other namespaces.

csharp

using System;

2. Resource Management: It ensures the proper disposal of resources by wrapping the resource
allocation and disposal code in a block.

csharp

using (var stream = new FileStream("file.txt", FileMode.Open))


{
// Use the stream
} // stream.Dispose() is called automatically

5. What are value types and reference types in C#? Give examples.

Value Types: Stored on the stack, hold their data directly. Examples: `int`, `float`, `char`,
`struct`.
Reference Types: Stored on the heap, hold a reference to their data. Examples: `object`,
`string`, `class`.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/40
Example:

csharp

int valueType = 10; // Value type


string referenceType = "Hello"; // Reference type

6. What is inheritance and how is it implemented in C#?

Inheritance is a fundamental OOP concept where a class (derived class) inherits properties and
methods from another class (base class). It promotes code reuse and polymorphism.
Example:

csharp

public class Animal


{
public void Eat() { Console.WriteLine("Eating"); }
}

public class Dog : Animal


{
public void Bark() { Console.WriteLine("Barking"); }
}

Dog dog = new Dog();


dog.Eat(); // Inherited method
dog.Bark(); // Derived class method

7. Explain polymorphism with an example in C#.

Polymorphism allows methods to have different implementations based on the object that invokes
them. It can be achieved through method overriding and interfaces.
Example:

csharp

public class Animal


{
public virtual void Speak() { Console.WriteLine("Animal speaks"); }
}

public class Dog : Animal


{
public override void Speak() { Console.WriteLine("Dog barks"); }
}

public class Cat : Animal


{
public override void Speak() { Console.WriteLine("Cat meows"); }
}

Animal myDog = new Dog();


Animal myCat = new Cat();
myDog.Speak(); // Output: Dog barks
myCat.Speak(); // Output: Cat meows

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/40
8. What are interfaces and abstract classes? How are they different?

Interfaces:
Define a contract with no implementation.
A class can implement multiple interfaces.
All members are public by default.
Example:

csharp

public interface IAnimal


{
void Speak();
}

public class Dog : IAnimal


{
public void Speak() { Console.WriteLine("Dog barks"); }
}

Abstract Classes:
Can have both abstract methods (no implementation) and regular methods (with
implementation).
A class can inherit only one abstract class.
Members can have different access modifiers.
Example:

csharp

public abstract class Animal


{
public abstract void Speak();
public void Eat() { Console.WriteLine("Eating"); }
}

public class Dog : Animal


{
public override void Speak() { Console.WriteLine("Dog barks"); }
}

9. What is encapsulation and how is it achieved in C#?

Encapsulation is an OOP principle that restricts direct access to an object's data and methods, allowing
controlled access through public methods. It is achieved using access modifiers (`private`,
`protected`, `public`).
Example:

csharp

public class Person


{
private string name;

public string GetName() { return name; }


public void SetName(string value) { name = value; }
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/40
Person person = new Person();
person.SetName("John");
Console.WriteLine(person.GetName()); // Output: John

10. Explain the concept of method overloading and method overriding with
examples.

Method Overloading: Defining multiple methods with the same name but different signatures
(parameters) in the same class.

csharp

public class MathOperations


{
public int Add(int a, int b) { return a + b; }
public double Add(double a, double b) { return a + b; }
}

MathOperations ops = new MathOperations();


Console.WriteLine(ops.Add(1, 2)); // Output: 3
Console.WriteLine(ops.Add(1.5, 2.5)); // Output: 4.0

Method Overriding: Providing a new implementation for a method inherited from a base class
using the `override` keyword.

csharp

public class Animal


{
public virtual void Speak() { Console.WriteLine("Animal speaks"); }
}

public class Dog : Animal


{
public override void Speak() { Console.WriteLine("Dog barks"); }
}

Dog dog = new Dog();


dog.Speak(); // Output: Dog barks

11. What are generics in C# and why are they useful?

Generics allow you to define type-safe data structures and methods without specifying the exact data
type. They enhance code reusability and type safety.
Example:

csharp

public class GenericList<T>


{
private List<T> items = new List<T>();

public void Add(T item) { items.Add(item); }


public T Get(int index) { return items[index]; }
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/40
GenericList<int> intList = new GenericList<int>();
intList.Add(1);
Console.WriteLine(intList.Get(0)); // Output: 1

GenericList<string> stringList = new GenericList<string>();


stringList.Add("Hello");
Console.WriteLine(stringList.Get(0)); // Output: Hello

12. Explain the difference between Array and ArrayList in C#.

Array:
Fixed size.
Strongly typed (all elements must be of the same type).
Better performance due to type safety.
Example:

csharp

int[] numbers = new int[5];


numbers[0] = 1;

ArrayList:
Dynamically resizable.
Not strongly typed (can store any type of objects).
Requires type casting when retrieving elements.
Example:

csharp

ArrayList list = new ArrayList();


list.Add(1);
list.Add("Hello");
int number = (int)list[0];

13. What is the difference between String and StringBuilder in C#?

String:
Immutable (modifications create new strings).
Less efficient for frequent modifications.
Example:

csharp

string str = "Hello";


str += " World"; // Creates a new string

StringBuilder:
Mutable (modifications are made in-place).
More efficient for frequent modifications.
Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/40
csharp

StringBuilder sb = new StringBuilder("Hello");


sb.Append(" World");
Console.WriteLine(sb.ToString()); // Output: Hello World

14. What is the purpose of the async and await keywords in C#?

The `async` and `await` keywords are used to write asynchronous code more easily. `async` is used to
declare an asynchronous method, and `await` is used to pause the execution until the awaited task
completes.
Example:

csharp

public async Task<string> GetDataAsync()


{
await Task.Delay(1000); // Simulate an asynchronous operation
return "Hello, Async World!";
}

public async Task CallAsyncMethod()


{
string result = await GetDataAsync();
Console.WriteLine(result); // Output: Hello, Async World!
}

15. Explain the use of delegates in C#.

A delegate is a type that represents references to methods with a specific parameter list and return
type. Delegates are used to pass methods as arguments to other methods.
Example:

csharp

public delegate void PrintDelegate(string message);

public class Printer


{
public void PrintMessage(string message) { Console.WriteLine(message); }
}

Printer printer = new Printer();


PrintDelegate printDel = new PrintDelegate(printer.PrintMessage);
printDel("Hello, Delegate!"); // Output: Hello, Delegate!

16. What is the difference between "ref" and "out" parameters in C#? When would
you use each one?

ref:
The parameter must be initialized before being passed.
Allows the method to modify the caller's variable.
Example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/40
csharp

public void Increment(ref int number) { number++; }

int value = 10;


Increment(ref value);
Console.WriteLine(value); // Output: 11

out:
The parameter does not need to be initialized before being passed.
The method must assign a value before it returns.
Example:

csharp

public void Initialize(out int number) { number = 10; }

int value;
Initialize(out value);
Console.WriteLine(value); // Output: 10

17. Describe the concept of serialization and deserialization in C#. How do you
implement it using attributes or interfaces?

Serialization is the process of converting an object into a format that can be easily stored or
transmitted, and deserialization is the process of converting the serialized format back into an object.
You can use attributes or interfaces to control serialization.
Example using `System.Text.Json`:

csharp

public class Person


{
public string Name { get; set; }
public int Age { get; set; }
}

Person person = new Person { Name = "John", Age = 30 };


string json = JsonSerializer.Serialize(person);
Person deserializedPerson = JsonSerializer.Deserialize<Person>(json);

Example using attributes:

csharp

public class Person


{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("age")]
public int Age { get; set; }
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/40
18. What is LINQ and how is it used in C#?

LINQ (Language Integrated Query) is a set of features that allows querying collections using a syntax
reminiscent of SQL. It provides a consistent way to query different data sources such as collections,
databases, and XML.
Example:

csharp

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = from num in numbers


where num % 2 == 0
select num;

foreach (var num in evenNumbers)


{
Console.WriteLine(num); // Output: 2, 4
}

var oddNumbers = numbers.Where(n => n % 2 != 0);


foreach (var num in oddNumbers)
{
Console.WriteLine(num); // Output: 1, 3, 5
}

C# Advanced Questions
1. Can you explain the difference between IEnumerable and IQueryable?

IEnumerable:
Represents a forward-only cursor of items.
Suitable for in-memory collections.
Deferred execution but queries are executed on the client-side.
Example:

csharp

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };


var evenNumbers = numbers.Where(n => n % 2 == 0);

IQueryable:
Extends `IEnumerable` to provide query capabilities against a data source.
Suitable for querying out-of-memory data like databases.
Deferred execution and queries are translated into SQL and executed on the server-side.
Example:

csharp

IQueryable<int> numbers = dbContext.Numbers;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/40
var evenNumbers = numbers.Where(n => n % 2 == 0);

2. What is a Dictionary in C# and how is it different from a List?

Dictionary:
A collection of key/value pairs.
Keys must be unique.
Fast lookups based on keys.
Example:

csharp

Dictionary<int, string> dict = new Dictionary<int, string>();


dict.Add(1, "One");
dict.Add(2, "Two");
string value = dict[1]; // Output: One

List:
A collection of items of the same type.
Supports duplicate items.
Indexed-based access.
Example:

csharp

List<string> list = new List<string>();


list.Add("One");
list.Add("Two");
string value = list[0]; // Output: One

3. Explain the concept of a lambda expression and provide an example.

A lambda expression is an anonymous function that can contain expressions and statements and can
be used to create delegates or expression tree types.
Example:

csharp

Func<int, int, int> add = (a, b) => a + b;


Console.WriteLine(add(2, 3)); // Output: 5

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };


var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4
}

4. What are anonymous types in C#?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/40
Anonymous types provide a way to create a new type without explicitly defining it. They are typically
used with LINQ queries to return a set of properties.
Example:

csharp

var person = new { Name = "John", Age = 30 };


Console.WriteLine(person.Name); // Output: John
Console.WriteLine(person.Age); // Output: 30

var students = new[] {


new { Name = "Alice", Age = 20 },
new { Name = "Bob", Age = 22 }
};
foreach (var student in students)
{
Console.WriteLine($"{student.Name}, {student.Age}");
}

Error Handling and Debugging


5. What is exception handling in C#?

Exception handling is a mechanism to handle runtime errors, allowing the program to continue
execution or fail gracefully. It is implemented using `try`, `catch`, and `finally` blocks.

6. Explain the difference between try-catch and try-catch-finally blocks.

try-catch:
Used to catch and handle exceptions.
Example:

csharp

try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}

try-catch-finally:
The `finally` block is used to execute code regardless of whether an exception is thrown or
not.
Example:

csharp

try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/40
{
Console.WriteLine("Cannot divide by zero.");
}
finally
{
Console.WriteLine("This block is always executed.");
}

7. What are extension methods in C#? How do you create and use extension
methods?

Extension methods allow you to add methods to existing types without modifying them. They are
defined as static methods in static classes and use the `this` keyword.
Example:

csharp

public static class StringExtensions


{
public static int WordCount(this string str)
{
return str.Split(' ').Length;
}
}

string sentence = "Hello world!";


int count = sentence.WordCount(); // Output: 2

8. Describe the use of delegates and events in C#. Provide an example of defining
and using delegates and events.

Delegates: A type that represents references to methods with a specific parameter list and
return type.
Events: A way for a class to notify other classes or objects when something of interest occurs.

Example:

csharp

public delegate void Notify(); // Delegate

public class Process


{
public event Notify ProcessCompleted; // Event

public void StartProcess()


{
// Process logic
OnProcessCompleted();
}

protected virtual void OnProcessCompleted()


{
ProcessCompleted?.Invoke();
}
}

public class Program


{
public static void Main()
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/40
{
Process process = new Process();
process.ProcessCompleted += Process_ProcessCompleted; // Subscribe
process.StartProcess();
}

private static void Process_ProcessCompleted()


{
Console.WriteLine("Process Completed");
}
}

9. How do you handle exceptions in C#? Explain the try-catch-finally block and
best practices for exception handling.

Use `try-catch-finally` blocks to handle exceptions.


Best practices:
Catch specific exceptions.
Log exceptions.
Avoid empty catch blocks.
Use `finally` for cleanup.

Example:

csharp

try
{
// Code that may throw an exception
}
catch (SpecificException ex)
{
// Handle specific exception
}
catch (Exception ex)
{
// Handle general exception
}
finally
{
// Cleanup code
}

10. What is the purpose of the "using" statement in C#? How is it related to
IDisposable?

The `using` statement ensures the proper disposal of resources that implement the `IDisposable`
interface. It automatically calls `Dispose` on the resource when the block is exited.
Example:

csharp

using (var stream = new FileStream("file.txt", FileMode.Open))


{
// Use the stream
} // stream.Dispose() is called automatically

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/40
11. Explain the differences between value types and reference types in C#.

Value Types:
Stored on the stack.
Contain the actual data.
Examples: `int`, `float`, `struct`.
Reference Types:
Stored on the heap.
Contain a reference to the data.
Examples: `object`, `string`, `class`.

Example:

csharp

int valueType = 10; // Value type


string referenceType = "Hello"; // Reference type

12. What is dependency injection (DI) in C#? How do you implement DI using
frameworks like ASP.NET Core DI or third-party libraries?

Dependency Injection (DI) is a design pattern that promotes loose coupling by injecting dependencies
into a class rather than creating them within the class. It is commonly implemented using DI
containers.
Example using ASP.NET Core DI:

csharp

public interface IService


{
void Serve();
}

public class Service : IService


{
public void Serve() { Console.WriteLine("Service Called"); }
}

public class Client


{
private readonly IService _service;

public Client(IService service)


{
_service = service;
}

public void Start()


{
_service.Serve();
}
}

// ConfigureServices method in Startup.cs


public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IService, Service>();
services.AddTransient<Client>();
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/40
// Using the service
public class Program
{
public static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddTransient<IService, Service>()
.AddTransient<Client>()
.BuildServiceProvider();

var client = serviceProvider.GetService<Client>();


client.Start();
}
}

13. How do you work with JSON data in C#? Describe serialization and
deserialization techniques.

Serialization: Converting an object to a JSON string.


Deserialization: Converting a JSON string to an object.

Example using `System.Text.Json`:

csharp

public class Person


{
public string Name { get; set; }
public int Age { get; set; }
}

// Serialization
Person person = new Person { Name = "John", Age = 30 };
string jsonString = JsonSerializer.Serialize(person);

// Deserialization
Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString);

14. What are nullable types in C#? How do you handle null values using nullable
types?

Nullable types allow value types to represent the normal range of values plus an additional `null`
value.
Example:

csharp

int? nullableInt = null;


if (nullableInt.HasValue)
{
Console.WriteLine($"Value: {nullableInt.Value}");
}
else
{
Console.WriteLine("No value assigned.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/40
15. Describe the concept of garbage collection in C#. How does the garbage
collector manage memory in .NET applications?

Garbage collection (GC) in .NET automatically manages memory by reclaiming unused objects. The GC
runs periodically, identifies objects that are no longer in use, and frees their memory.
Key concepts:

Generations: Objects are grouped into generations (0, 1, 2) to optimize collection.


Finalization: Objects can override `Finalize` to perform cleanup before GC.
Dispose Pattern: Implement `IDisposable` to provide deterministic cleanup.

Example:

csharp

public class Resource : IDisposable


{
private bool disposed = false;

public void Dispose()


{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)


{
if (!disposed)
{
if (disposing)
{
// Free managed resources
}
// Free unmanaged resources
disposed = true;
}
}

~Resource()
{
Dispose(false);
}
}

ASP.NET Core MVC Questions


1. What are the key differences between ASP.NET Core MVC and ASP.NET MVC?

Cross-Platform: ASP.NET Core MVC is cross-platform, whereas ASP.NET MVC is Windows-only.


Performance: ASP.NET Core MVC offers better performance due to its modular framework and
optimizations.
Dependency Injection: Built-in support for DI in ASP.NET Core MVC, whereas ASP.NET MVC
requires third-party libraries.
Configuration: ASP.NET Core uses a unified configuration system, while ASP.NET MVC uses
web.config files.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/40
Middleware: ASP.NET Core MVC relies on a middleware pipeline, replacing the old HTTP modules
and handlers.

2. Explain the Middleware concept in ASP.NET Core. How does the Middleware
pipeline work?

Middleware in ASP.NET Core are components that handle HTTP requests and responses. The
middleware pipeline processes requests and responses sequentially. Each middleware component
can:

Pass the request to the next component.


Short-circuit the pipeline and send a response.
Modify the request or response.

Example:

csharp

public void Configure(IApplicationBuilder app)


{
app.Use(async (context, next) =>
{
// Middleware logic before next component
await next.Invoke();
// Middleware logic after next component
});

app.Run(async context =>


{
await context.Response.WriteAsync("Hello, World!");
});
}

3. What is Dependency Injection (DI) in ASP.NET Core? How do you register and use
services using DI?

Dependency Injection (DI) is a design pattern used to implement IoC, allowing the creation of
dependent objects outside of a class and providing those objects to the class. ASP.NET Core has built-
in support for DI.
Registering Services:

csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddTransient<IService, Service>();
}

Using Services:

csharp

public class HomeController : Controller


{

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/40
private readonly IService _service;

public HomeController(IService service)


{
_service = service;
}

public IActionResult Index()


{
_service.Serve();
return View();
}
}

4. Describe the role of ConfigureServices and Configure methods in the Startup


class of an ASP.NET Core application.

ConfigureServices: Used to register services with the DI container. This method is called by the
runtime before the `Configure` method.

csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddControllersWithViews();
}

Configure: Defines the middleware pipeline and handles how the application responds to HTTP
requests.

csharp

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

5. What is Razor Pages in ASP.NET Core? How is it different from the MVC pattern?

Razor Pages is a page-based model for building web UI, introduced in ASP.NET Core 2.0. It focuses on
a page-centric approach, simplifying the development of page-focused scenarios.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/40
Differences:

Structure: Razor Pages are organized by page, with each page having its own `PageModel` class.
Routing: Razor Pages use a folder-based routing model, while MVC uses controller-based
routing.
Use Case: Razor Pages are ideal for simple, page-focused applications, whereas MVC is suited for
complex, controller-centric applications.

6. How do you handle routing in ASP.NET Core MVC? Explain attribute routing and
convention-based routing.

Convention-based Routing: Defined in the `Startup` class using a routing pattern.

csharp

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

Attribute Routing: Defined by placing route attributes on controller actions.

csharp

[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Action logic
}
}

7. What are Tag Helpers in ASP.NET Core? Provide examples of built-in Tag Helpers
and how to create custom Tag Helpers.

Tag Helpers are components that help you render HTML elements in Razor views. They provide server-
side processing of HTML elements.
Examples:

Built-in Tag Helpers:

html

<form asp-action="Index">
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<button type="submit">Submit</button>
</form>

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/40
Custom Tag Helper:

csharp

[HtmlTargetElement("email")]
public class EmailTagHelper : TagHelper
{
public string Address { get; set; }
public string Domain { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
output.TagName = "a";
output.Attributes.SetAttribute("href", $"mailto:{Address}@{Domain}");
output.Content.SetContent($"{Address}@{Domain}");
}
}

8. Explain the use of View Components and Partial Views in ASP.NET Core MVC.
How do they differ from each other?

View Components:
Designed to encapsulate reusable rendering logic.
Similar to partial views but more powerful, allowing for complex logic and dependency
injection.
Example:

csharp

public class PriorityListViewComponent : ViewComponent


{
private readonly IPriorityService _service;

public PriorityListViewComponent(IPriorityService service)


{
_service = service;
}

public IViewComponentResult Invoke(int maxPriority)


{
var items = _service.GetPriorities(maxPriority);
return View(items);
}
}

Usage in Razor view:

html

@await Component.InvokeAsync("PriorityList", new { maxPriority = 5 })

Partial Views:
Reusable components for rendering HTML.
Do not have the same level of encapsulation or dependency injection capabilities.
Example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 27/40
html

@await Html.PartialAsync("_PartialViewName")

9. Describe the differences between TempData, ViewData, and ViewBag in ASP.NET


Core MVC for passing data between controllers and views.

TempData:
Stores data for the duration of an HTTP request.
Useful for redirection.
Example:

csharp

TempData["Message"] = "Data saved successfully!";

ViewData:
Dictionary for passing data from controller to view.
Not strongly typed.
Example:

csharp

ViewData["Message"] = "Hello, World!";

ViewBag:
Dynamic property for passing data from controller to view.
Not strongly typed.
Example:

csharp

ViewBag.Message = "Hello, World!";

10. What is ASP.NET Core Identity? How do you implement authentication and
authorization using Identity in ASP.NET Core MVC?

ASP.NET Core Identity is a membership system for adding login functionality to applications. It
supports authentication and authorization.
Implementing Identity:

Configure Services:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 28/40
csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddDbContext<ApplicationDbContext>(options =>

options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
}

Configure Middleware:

csharp

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}

11. How do you handle form submissions and validation in ASP.NET Core MVC?
Describe the use of model validation attributes.

Model Binding: Automatically maps form fields to model properties.


Validation Attributes: Used to enforce validation rules.

csharp

public class UserModel


{
[Required]
public string Name { get; set; }

[EmailAddress]
public string Email { get; set; }
}

Handling Form Submission:

csharp

[HttpPost]
public IActionResult Submit(UserModel model)
{
if (ModelState.IsValid)
{
// Process data
return RedirectToAction("Success");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/40
return View(model);
}

12. Explain the concept of Entity Framework Core (EF Core) in ASP.NET Core MVC
for database access. How do you perform CRUD operations using EF Core?

EF Core is an ORM for .NET applications to interact with databases using .NET objects.
Example:

DbContext:

csharp

public class ApplicationDbContext : DbContext


{
public DbSet<User> Users { get; set; }
}

CRUD Operations:

csharp

// Create
var user = new User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();

// Read
var user = context.Users.Find(1);

// Update
user.Name = "Jane";
context.Users.Update(user);
context.SaveChanges();

// Delete
context.Users.Remove(user);
context.SaveChanges();

13. What is Middleware Authorization in ASP.NET Core? How do you implement


role-based or policy-based authorization?

Middleware Authorization ensures that requests meet certain criteria before reaching protected
resources.

Role-based Authorization:

csharp

[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
return View();
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/40
Policy-based Authorization:

csharp

services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin"));
});

[Authorize(Policy = "RequireAdmin")]
public IActionResult AdminOnly()
{
return View();
}

14. Describe the use of Areas in ASP.NET Core MVC for organizing controllers,
views, and other resources in large applications.

Areas allow partitioning a large application into smaller functional groups, each with its own
controllers, views, and models.
Example:

Define Area:

csharp

[Area("Admin")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}

Route Configuration:

csharp

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
});

15. How do you work with client-side libraries and frameworks (such as jQuery,
Bootstrap, etc.) in an ASP.NET Core MVC application?

LibMan: Library Manager for managing client-side libraries.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 31/40
bash

libman install jquery --provider unpkg

Include in Layout:

html

<script src="~/lib/jquery/jquery.js"></script>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css" />

Basics and Architecture

1. What is ASP.NET Core MVC and how does it differ from ASP.NET MVC?

ASP.NET Core MVC is a lightweight, open-source, and cross-platform framework for building web apps
and APIs. Differences include better performance, built-in DI, and a unified configuration system.

2. Explain the Model-View-Controller (MVC) pattern. How does it work in ASP.NET Core MVC?

The MVC pattern separates an application into three main components:

Model: Manages data and business logic.


View: Handles the display of information.
Controller: Processes user input and interacts with the Model to render the final output via the
View.

Middleware

1. What is Middleware in ASP.NET Core? How does the Middleware pipeline work?

Middleware are software components that process requests and responses. They form a pipeline that
handles HTTP requests. Each middleware component can process a request, call the next middleware,
or short-circuit the pipeline.

2. Can you give an example of a custom Middleware you have created?

Example:

csharp

public class CustomMiddleware


{
private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)


{
_next = next;
}

public async Task Invoke(HttpContext context)


{

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/40
// Custom logic before next middleware
await _next(context);
// Custom logic after next middleware
}
}

Register in `Startup`:

csharp

public void Configure(IApplicationBuilder app)


{
app.UseMiddleware<CustomMiddleware>();
}

Dependency Injection

1. What is Dependency Injection (DI) in ASP.NET Core MVC? How do you register and use services
with DI?

DI is a design pattern for managing dependencies. Register services in `ConfigureServices` and inject
them via constructor.

2. How do you configure services in the Startup class?

csharp

public void ConfigureServices(IServiceCollection services)


{
services.AddTransient<IService, Service>();
}

Routing

1. Explain the difference between conventional routing and attribute routing in ASP.NET Core
MVC.

Conventional Routing: Defined in `Startup` with route patterns.


Attribute Routing: Defined using attributes on controllers and actions.

2. How do you define and use attribute routes?

Example:

csharp

[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 33/40
// Action logic
}
}

Controllers and Actions

1. What are Controllers in ASP.NET Core MVC? How do you create a controller?

Controllers handle incoming HTTP requests, process them, and return responses.
Example:

csharp

public class HomeController : Controller


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

2. Explain how action methods work in ASP.NET Core MVC. How do you return different types of
responses?

Action methods handle requests and return responses, such as views, JSON, or status codes.
Example:

csharp

public IActionResult Index()


{
return View();
}

public IActionResult GetJson()


{
return Json(new { Name = "John" });
}

Views

1. What is Razor in ASP.NET Core MVC? How do you use Razor syntax in views?

Razor is a markup syntax for embedding server-based code in web pages. Razor syntax uses `@` to
switch between HTML and C#.
Example:

html

@{
var message = "Hello, World!";
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/40
<p>@message</p>

2. Explain the difference between ViewData, ViewBag, and TempData.

ViewData: Dictionary for passing data from controller to view.


ViewBag: Dynamic property for passing data from controller to view.
TempData: Stores data for the duration of an HTTP request and useful for redirection.

Models and Data Binding

1. How do you bind data to a model in ASP.NET Core MVC?

ASP.NET Core MVC automatically binds form data to model properties based on matching names.

2. What are model validation attributes? How do you perform model validation?

Validation attributes enforce validation rules on model properties.


Example:

csharp

public class UserModel


{
[Required]
public string Name { get; set; }

[EmailAddress]
public string Email { get; set; }
}

View Components and Partial Views

1. What are View Components in ASP.NET Core MVC? How do they differ from Partial Views?

View Components are similar to partial views but more powerful, allowing encapsulation of reusable
rendering logic with dependency injection.

2. Provide an example of how to create and use a View Component.

Example:

csharp

public class PriorityListViewComponent : ViewComponent


{
private readonly IPriorityService _service;

public PriorityListViewComponent(IPriorityService service)


{
_service = service;
}

public IViewComponentResult Invoke(int maxPriority)

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 35/40
{
var items = _service.GetPriorities(maxPriority);
return View(items);
}
}

Usage in Razor view:

html

@await Component.InvokeAsync("PriorityList", new { maxPriority = 5 })

Authentication and Authorization

1. How do you implement authentication in ASP.NET Core MVC using ASP.NET Core Identity?

Configure Identity in `Startup` and use `SignInManager` and `UserManager` for handling authentication.

2. Explain role-based and policy-based authorization in ASP.NET Core MVC.

Role-based Authorization: Restricts access based on user roles.

csharp

[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
return View();
}

Policy-based Authorization: Defines policies with multiple requirements.

csharp

services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin"));
});

[Authorize(Policy = "RequireAdmin")]
public IActionResult AdminOnly()
{
return View();
}

Entity Framework Core

1. How do you use Entity Framework Core (EF Core) in ASP.NET Core MVC for database access?

Configure DbContext in `Startup` and use it to interact with the database.

2. Provide an example of how to perform CRUD operations using EF Core.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/40
Example:

csharp

public class ApplicationDbContext : DbContext


{
public DbSet<User> Users { get; set; }
}

// Create
var user = new User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();

// Read
var user = context.Users.Find(1);

// Update
user.Name = "Jane";
context.Users.Update(user);
context.SaveChanges();

// Delete
context.Users.Remove(user);
context.SaveChanges();

Asynchronous Programming

1. How do you implement asynchronous action methods in ASP.NET Core MVC?

Use the `async` and `await` keywords in action methods.


Example:

csharp

public async Task<IActionResult> Index()


{
var data = await _service.GetDataAsync();
return View(data);
}

2. Why is asynchronous programming important in web applications?

Asynchronous programming improves scalability and responsiveness by not blocking threads during
long-running operations.

Tag Helpers

1. What are Tag Helpers in ASP.NET Core MVC? Provide examples of built-in Tag Helpers.

Tag Helpers enable server-side code to participate in creating and rendering HTML elements.
Examples:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 37/40
html

<form asp-action="Index">
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<button type="submit">Submit</button>
</form>

2. How do you create and use a custom Tag Helper?

Example:

csharp

[HtmlTargetElement("email")]
public class EmailTagHelper : TagHelper
{
public string Address { get; set; }
public string Domain { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
output.TagName = "a";
output.Attributes.SetAttribute("href", $"mailto:{Address}@{Domain}");
output.Content.SetContent($"{Address}@{Domain}");
}
}

Exception Handling

1. How do you handle exceptions in ASP.NET Core MVC? Explain the use of exception filters and
middleware.

Use exception filters or middleware to handle exceptions.


Example:

csharp

public class CustomExceptionFilter : IExceptionFilter


{
public void OnException(ExceptionContext context)
{
// Handle exception
}
}

Middleware:

csharp

app.UseMiddleware<ExceptionHandlingMiddleware>();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 38/40
2. What is the difference between handling exceptions in middleware and in exception filters?

Middleware: Handles exceptions for the entire application.


Exception Filters: Handles exceptions at the MVC action level.

Logging and Diagnostics

1. How do you implement logging in an ASP.NET Core MVC application?

Use the built-in logging framework to log messages.


Example:

csharp

private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)


{
_logger = logger;
}

public IActionResult Index()


{
_logger.LogInformation("Index action called");
return View();
}

2. Explain how to use the built-in logging framework in ASP.NET Core.

Configure logging in `Startup` and inject `ILogger` into controllers or services.

Testing

1. How do you unit test controllers in ASP.NET Core MVC?

Use xUnit or NUnit along with mocking frameworks like Moq to test controllers.
Example:

csharp

public class HomeControllerTests


{
private readonly HomeController _controller;
private readonly Mock<IService> _mockService;

public HomeControllerTests()
{
_mockService = new Mock<IService>();
_controller = new HomeController(_mockService.Object);
}

[Fact]
public void Index_ReturnsViewResult()
{
var result = _controller.Index();
Assert.IsType<ViewResult>(result);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 39/40
}
}

2. What tools and frameworks do you use for testing ASP.NET Core MVC applications?

xUnit: A testing framework for .NET.


Moq: A mocking library for .NET.
Selenium: For automated UI testing.

These tools and frameworks help in creating comprehensive tests for different layers of the
application.
Is this conversation helpful so far?
ChatGPT can make mistakes. Check important info.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 40/40

You might also like