Unit 6: Asp.Net With Web API - Subjective Questions
INT402 — Modern Web Programming Tools And Techniques • Practice Questions with Detailed Answers
20 questions
Define REST. Explain the concepts of resources, representations, and resource URIs in RESTful services.
REST (Representational State Transfer) is an architectural style used to design distributed applications and web services. A RESTful service exposes application data and functionality as resources that can be accessed through standard HTTP methods.
- Resource: Any entity or information exposed by the service, such as a product, student, employee, or order.
- Resource URI: A unique address used to identify a resource. For example,
/api/products/10identifies the product whose ID is10. - Representation: The format in which the current state of a resource is transferred. JSON and XML are common representation formats.
- HTTP methods: Operations are performed using methods such as
GET,POST,PUT,PATCH, andDELETE.
For example, GET /api/products/10 retrieves a representation of product 10, usually in JSON format. REST focuses on resources rather than method-oriented URLs such as /GetProductById.
Explain the major architectural constraints of REST and discuss how they improve a web service.
A RESTful system is based on the following architectural constraints:
- Client-server separation: The client manages the user interface, while the server manages data and business logic. This separation allows both sides to evolve independently.
- Statelessness: Every request must contain all information required for processing. The server does not store client session state between requests.
- Cacheability: Responses should indicate whether they can be cached. Caching reduces server load and improves response time.
- Uniform interface: Resources are identified through URIs and manipulated using standard HTTP methods and representations.
- Layered system: A client may communicate through proxies, gateways, or load balancers without knowing the server's internal structure.
- Code on demand, optional: The server may provide executable code, such as JavaScript, to extend client functionality.
These constraints provide scalability, simplicity, portability, loose coupling, reliability, and better performance. Statelessness is especially useful for load balancing because any server can process any request.
Describe the roles of the HTTP methods GET, POST, PUT, PATCH, and DELETE in a RESTful Web API. Mention suitable HTTP status codes.
RESTful APIs use HTTP methods to express operations on resources:
- GET: Retrieves one or more resources. Successful requests normally return
200 OK; an unknown resource may return404 Not Found. - POST: Creates a new resource. A successful creation should return
201 Created, usually with the URI of the new resource. - PUT: Completely replaces or updates a resource at a known URI. It commonly returns
200 OKor204 No Content. - PATCH: Partially updates selected fields of an existing resource. It commonly returns
200 OKor204 No Content. - DELETE: Removes a resource. It normally returns
204 No Content; if the resource does not exist,404 Not Foundmay be returned.
GET, PUT, and DELETE are generally idempotent, meaning repeated identical requests should have the same intended effect as one request. POST is generally not idempotent because repeated requests may create multiple resources.
Distinguish between REST and SOAP web services.
REST and SOAP differ in architecture, message format, and usage:
| Basis | REST | SOAP |
|---|---|---|
| Nature | Architectural style | Formal messaging protocol |
| Data format | Commonly JSON; can also use XML or text | Primarily XML |
| Interface | Uses resources, URIs, and HTTP methods | Uses operations defined in a service contract |
| Contract | Can use OpenAPI but does not require it | Commonly uses WSDL |
| Transport | Usually HTTP or HTTPS | Can use HTTP, SMTP, and other protocols |
| Overhead | Lightweight | Higher XML and protocol overhead |
| State | Usually stateless | Can support stateless or stateful operations |
| Caching | HTTP caching is directly supported | Not naturally based on HTTP caching |
REST is usually preferred for browser, mobile, and public web APIs because it is simple and lightweight. SOAP may be appropriate for enterprise systems that require strict contracts, advanced message security, and formal transaction standards.
What is ASP.NET Web API? Explain its important features and request-processing components.
ASP.NET Web API is a framework for building HTTP services that can be consumed by browsers, mobile applications, desktop programs, and other clients. It is commonly used to create RESTful services on the .NET platform.
Important features include:
- Support for standard HTTP methods.
- Automatic conversion of objects into JSON or XML through media-type formatters.
- Model binding and model validation.
- Convention-based and attribute-based routing.
- HTTP response and status-code control.
- Filters for authorization, exception handling, and other cross-cutting concerns.
- Dependency injection and asynchronous action support.
Basic request flow:
- The client sends an HTTP request.
- The routing system matches the URI to a controller and action.
- Model binding converts request data into .NET objects.
- The controller executes business or database logic.
- A response object and status code are produced.
- A formatter serializes the response as JSON or XML.
A Web API controller commonly inherits from ApiController in ASP.NET Web API 2.
Compare an ASP.NET MVC controller with an ASP.NET Web API controller.
An ASP.NET MVC controller and an ASP.NET Web API controller serve different primary purposes:
- An MVC controller is designed mainly to return HTML views for web applications.
- A Web API controller is designed mainly to return data and HTTP responses for API clients.
- MVC actions commonly return
ActionResult,ViewResult, or rendered HTML. - Web API actions may return domain objects,
IHttpActionResult, orHttpResponseMessage. - MVC selects actions using routes and action names, whereas Web API also uses the HTTP method as an important part of action selection.
- Web API uses media-type formatters to serialize objects into JSON or XML.
- MVC commonly binds data from forms, routes, and query strings, while Web API also binds structured request bodies.
In ASP.NET Web API 2, an API controller typically inherits from ApiController. Although both technologies use controllers, routing, filters, and model binding, Web API is more suitable when the output is data rather than a rendered web page.
Describe the steps required to create and run the first ASP.NET Web API project.
A basic ASP.NET Web API project can be created as follows:
- Open Visual Studio and select Create a new project.
- Choose the appropriate ASP.NET Web Application template and select the Web API option.
- Provide the project name, location, and framework version.
- Examine the generated folders, especially
Controllers,Models, andApp_Start. - Add a model such as
Productwith properties likeId,Name, andPrice. - Add a controller such as
ProductsControllerthat inherits fromApiController. - Create a
GETaction, for example:public IEnumerable<Product> Get() { return products; }. - Confirm that Web API routing is registered in
WebApiConfig. - Build the project and correct any compilation errors.
- Run the application using IIS Express.
- Access a URL such as
/api/productsthrough a browser or Postman. - Verify the JSON or XML response and the HTTP status code.
The default convention-based route is commonly api/{controller}/{id}, where id is optional. Therefore, /api/products/5 is normally directed to ProductsController with an ID value of 5.
Explain the purpose of models, controllers, model binding, and media-type formatters in ASP.NET Web API.
The major elements of an ASP.NET Web API application have the following purposes:
- Model: Represents the structure and rules of application data. For example, a
Productmodel may containId,Name, andPriceproperties. - Controller: Receives HTTP requests, coordinates business or database operations, and returns an HTTP response. A controller normally contains actions corresponding to HTTP methods.
- Model binding: Converts values from the route, query string, headers, or request body into action parameters and .NET objects.
- Media-type formatter: Serializes response objects and deserializes request bodies. JSON and XML formatters are commonly available.
For example, when a client sends a JSON object using POST, the JSON formatter converts it into a Product object. The controller validates and saves the object, then returns a response. The formatter converts the returned .NET object back into JSON or XML according to content negotiation.
Describe how to create and configure a database for an ASP.NET Web API using Entity Framework.
A database-backed Web API can be configured using Entity Framework through these steps:
- Create entity classes: Define classes such as
Productwith properties including a primary key. - Install Entity Framework: Add the required Entity Framework package to the project if it is not already available.
- Create a context: Define a class derived from
DbContextand expose tables throughDbSet<T>properties, such asDbSet<Product> Products. - Add a connection string: Configure the SQL Server connection in
Web.configusing a name that matches the context configuration. - Enable migrations: Run the migration command that prepares the project for schema changes.
- Create a migration: Generate a migration from the entity classes.
- Update the database: Apply the migration so that tables and constraints are created.
- Inject or instantiate the context: Use the context in the API controller or, preferably, through a service or repository.
- Perform CRUD operations: Use methods such as
Add,Find,Remove, andSaveChanges.
Entity Framework maps .NET classes to database tables and tracks changes to objects. Migrations allow the schema to evolve without manually recreating the database. In a production application, connection strings and credentials must be secured, and database access should normally be asynchronous.
Explain the relationship among an entity class, DbContext, DbSet, and a database connection string.
These components work together to connect a Web API to a relational database:
- Entity class: Represents a row of a database table. For example, each
Productobject represents one product record. DbContext: Represents a session with the database. It manages connections, queries, change tracking, and persistence.DbSet<T>: Represents a collection of entities of a particular type and usually maps to a table. For example,DbSet<Product>maps to the products table.- Connection string: Contains information such as the database server, database name, and authentication method.
When a controller queries context.Products, Entity Framework translates the LINQ expression into SQL. When the controller modifies an entity and calls SaveChanges, Entity Framework generates the required INSERT, UPDATE, or DELETE statement. Thus, the entity defines the data structure, DbSet provides table-like access, DbContext coordinates database work, and the connection string identifies the target database.
Explain how GET operations are implemented for retrieving all records and a single record in ASP.NET Web API.
Two common GET operations are required in a CRUD API:
- Retrieve all records: A parameterless
GETaction queries the entity set and returns a collection. For example, a request toGET /api/productscan return all products with200 OK. - Retrieve one record: A
GETaction accepts an ID, searches the database, and returns the matching entity. For example,GET /api/products/5retrieves product5.
A single-record action should follow this logic:
- Read the ID from the route.
- Search the database using
Find,SingleOrDefault, or an equivalent asynchronous operation. - If no record is found, return
404 Not Found. - If a record is found, return it with
200 OK.
Collection endpoints may also support query parameters for filtering, sorting, and paging, such as /api/products?page=2&pageSize=10. Production APIs should avoid returning unbounded database tables because large responses consume memory and network bandwidth.
Describe how a POST operation creates a new database record in ASP.NET Web API.
A POST operation is used to create a new resource. Its typical processing steps are:
- The client sends JSON in the request body to an endpoint such as
POST /api/products. - The formatter and model binder convert the JSON into a model object.
- The controller checks
ModelState.IsValidor performs equivalent validation. - If the input is invalid, the API returns
400 Bad Requestwith validation details. - If valid, the entity is added to the relevant
DbSet. SaveChangesorSaveChangesAsyncinserts the record into the database.- The API returns
201 Created. - The response should include the newly created object and a
Locationheader containing its URI.
For example, a product request may contain {"name":"Keyboard","price":1500}. The database normally generates the ID. The response can identify the created resource using a URI such as /api/products/21. This follows REST principles more accurately than returning only a generic success message.
Compare PUT and PATCH, and explain how an update operation should handle validation, missing resources, and database persistence.
PUT and PATCH are both used for updates, but they have different meanings:
PUTnormally replaces the complete state of a resource. The client sends all replaceable fields.PATCHapplies a partial modification. The client sends only the fields or operations that must change.
A reliable update operation should:
- Extract the resource ID from the URI.
- Validate the request body.
- Ensure that the route ID matches any ID supplied in the body.
- Search for the existing database record.
- Return
404 Not Foundif the resource does not exist. - Apply the permitted changes to the tracked entity.
- Prevent modification of protected fields such as generated IDs or audit values.
- Save the changes with
SaveChangesorSaveChangesAsync. - Return
200 OKwith the updated representation or204 No Content.
Concurrent modifications should be handled using a timestamp, row-version field, or another concurrency token. If a concurrency conflict is detected, the API may return 409 Conflict or 412 Precondition Failed. PUT is expected to be idempotent, while the idempotence of PATCH depends on the patch operation.
Explain the implementation and expected responses of a DELETE operation in ASP.NET Web API.
A DELETE operation removes a resource identified by its URI. For example, DELETE /api/products/5 requests the removal of product 5.
The controller should perform the following steps:
- Accept the ID from the route.
- Search the database for the matching entity.
- If it does not exist, return
404 Not Found. - If it exists, remove it from the appropriate
DbSet. - Call
SaveChangesorSaveChangesAsync. - Return
204 No Contentafter successful deletion.
Some APIs return 200 OK with the deleted object, but 204 No Content is common when no response body is required. A repeated deletion should not recreate or further change the resource, so DELETE is considered idempotent. The API must also consider foreign-key constraints, authorization, and whether the application requires permanent deletion or a soft delete, in which a status field is changed instead of physically removing the row.
Describe the complete request-response flow for CRUD operations in a database-backed ASP.NET Web API.
The complete CRUD request-response flow is as follows:
- Request creation: The client sends an HTTP request containing a method, URI, headers, and possibly a request body.
- Routing: Convention or attribute routing determines the controller and action.
- Authentication and authorization: Security components identify the client and verify permissions.
- Model binding: Route, query, and body values are converted into action parameters or model objects.
- Validation: Data annotations and business rules are checked. Invalid input should produce
400 Bad Request. - Controller or service execution: The action calls a service, repository, or Entity Framework context.
- Database operation:
GETperforms a query.POSTinserts an entity.PUTorPATCHupdates an entity.DELETEremoves or deactivates an entity.
- Persistence: Entity Framework generates SQL and saves changes within an appropriate transaction.
- Response construction: The API chooses a status such as
200,201,204,400, or404. - Content negotiation: A formatter serializes the response object, commonly as JSON.
- Client processing: The client reads the status, headers, and response body.
Controllers should remain thin, while business rules and data-access logic should be placed in separate services where possible. Exceptions should be converted into consistent responses without exposing sensitive implementation details.
Explain how Postman can be used to test all CRUD operations of an ASP.NET Web API.
Postman allows API requests to be created, sent, inspected, and saved. CRUD operations can be tested as follows:
- GET all: Select
GET, enter/api/products, send the request, and verify200 OKand the JSON array. - GET one: Send
GET /api/products/5and verify the returned object or404 Not Found. - POST: Select
POST, setContent-Type: application/json, choose a raw JSON body, and send a new object. Verify201 Created, the response body, and theLocationheader. - PUT or PATCH: Send the updated JSON to
/api/products/5using the appropriate method. Verify200 OKor204 No Contentand retrieve the record again to confirm the change. - DELETE: Send
DELETE /api/products/5, expect204 No Content, and use a laterGETto confirm removal.
Postman can also test authorization headers, query parameters, invalid data, unknown IDs, and unsupported HTTP methods. Test scripts can assert results such as pm.response.code === 200. Environment variables may store values such as baseUrl and authentication tokens, while collections organize related requests for repeated or automated execution.
What is convention-based routing in ASP.NET Web API? Explain the structure and working of a default route.
Convention-based routing uses centrally defined route templates to map incoming URIs to controllers and actions. Routes are commonly registered in WebApiConfig.
A typical route template is api/{controller}/{id}, where:
apiis a fixed URI segment.{controller}is replaced by the controller name without theControllersuffix.{id}is a route parameter and is commonly optional.
For example:
/api/productsmaps toProductsController./api/products/5maps toProductsControllerwithid = 5.
After selecting the controller, Web API considers the HTTP method and action parameter compatibility. A GET request may select a method named Get, while a POST request may select Post.
Convention-based routing is concise and provides a uniform URL structure. However, specialized nested or action-specific URLs can be difficult to express. Route order is important because the routing system checks registered routes in sequence and generally uses the first matching route.
Explain attribute routing in ASP.NET Web API with suitable route-prefix, parameter, and constraint examples.
Attribute routing defines route templates directly on controllers and action methods. It is enabled by calling MapHttpAttributeRoutes during Web API configuration.
Important attributes include:
RoutePrefix: Defines a common prefix for all routes in a controller, such asapi/products.Route: Defines the route for an individual action, such as{id}orcategory/{name}.- HTTP method attributes:
HttpGet,HttpPost,HttpPut, andHttpDeleterestrict the accepted method. - Route constraints: Restrict parameter values, such as
{id:int}for an integer ID or{id:int:min(1)}for a positive integer.
For example, a controller may use a prefix of api/products, while a GET action uses the route {id:int}. The URL /api/products/8 then maps to that action only when the parameter is an integer.
Attribute routing supports readable custom URLs, multiple routes for an action, route names, optional parameters, defaults, and constraints. It is especially useful for nested resources and API versioning.
Compare convention-based routing and attribute routing. How are ambiguous routes and route conflicts prevented?
Convention-based routing stores route templates in a central configuration file. It is suitable for APIs that follow a consistent pattern such as api/{controller}/{id}. It reduces repeated route declarations and gives the application a uniform structure.
Attribute routing places route information close to controller actions. It supports custom paths, nested resources, constraints, versioning, and different URI patterns more naturally.
Major comparison:
- Convention routing is centralized; attribute routing is action-oriented.
- Convention routing is simpler for standard CRUD controllers.
- Attribute routing is more flexible for complex API structures.
- Convention routes depend heavily on route order and naming conventions.
- Attribute routes can clearly specify method attributes and parameter constraints.
Conflicts can be prevented by:
- Adding constraints such as
{id:int}and{name:alpha}. - Using explicit HTTP method attributes.
- Avoiding multiple actions with identical route templates and methods.
- Placing specific convention routes before general routes.
- Giving routes meaningful names when generating links.
- Using unique prefixes for API areas or versions.
- Testing all route combinations with valid and invalid values.
An ambiguous match occurs when more than one action appears equally valid. Clear templates, method restrictions, and type constraints make route selection deterministic.
Discuss good practices for validation, error handling, status codes, and security while building and testing an ASP.NET Web API.
A robust ASP.NET Web API should apply the following practices:
Validation:
- Use data annotations and check model validation before database operations.
- Validate business rules in a service layer.
- Return
400 Bad Requestwith field-specific errors for invalid input. - Use data-transfer objects to prevent clients from changing protected properties.
Error handling:
- Return
404 Not Foundfor unknown resources. - Return
409 Conflictfor relevant duplicate or concurrency conflicts. - Use centralized exception handling or exception filters.
- Log technical details on the server, but do not expose stack traces or database information to clients.
- Return errors in a consistent JSON structure.
Security:
- Use HTTPS to protect data in transit.
- Authenticate users with an appropriate token-based mechanism.
- Apply authorization at the controller or action level.
- Validate and constrain all client input.
- Store connection strings and secrets securely.
- Use parameterized database access through Entity Framework to reduce injection risks.
Testing:
- Test successful and unsuccessful CRUD scenarios in Postman.
- Verify status codes, response bodies, headers, and response times.
- Test missing fields, invalid types, unknown IDs, unauthorized requests, and malformed JSON.
- Save requests in collections and use automated Postman assertions.
These practices make the API predictable, secure, maintainable, and easier for clients to consume.
Define REST. Explain the concepts of resources, representations, and resource URIs in RESTful services.
REST (Representational State Transfer) is an architectural style used to design distributed applications and web services. A RESTful service exposes application data and functionality as resources that can be accessed through standard HTTP methods.
- Resource: Any entity or information exposed by the service, such as a product, student, employee, or order.
- Resource URI: A unique address used to identify a resource. For example,
/api/products/10identifies the product whose ID is10. - Representation: The format in which the current state of a resource is transferred. JSON and XML are common representation formats.
- HTTP methods: Operations are performed using methods such as
GET,POST,PUT,PATCH, andDELETE.
For example, GET /api/products/10 retrieves a representation of product 10, usually in JSON format. REST focuses on resources rather than method-oriented URLs such as /GetProductById.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →