Popular
Travel  |   Sports  |   Kids  |   Interview Tips  |   Entertainment  |   Fashion & Beauty  |   Trending  |   India  |   Spirituality  |   Environment   

Top 16 ASP.NET Web API Interview Type Questions

16072024WebAPIInterviewquestions.jpg

Top 16 ASP.NET Web API Interview Type Questions

Q1. What are Request Verbs or HTTP Verbs?

Request verbs, or HTTP verbs, are methods used in HTTP requests to specify the desired action to be performed on the identified resource. The most commonly used HTTP verbs are:

GET: Retrieves data from the server.

POST: Submits new data to the server.

PUT: Updates existing data on the server.

DELETE: Removes data from the server.

PATCH: Partially updates data on the server.

OPTIONS: Describes the communication options for the target resource.

Q2. What is the Request Header?

The request header is a part of the HTTP request that contains key-value pairs of metadata. This metadata provides essential information about the request context and helps the server understand how to process the request. Common request headers include:

Host: Specifies the domain name of the server (e.g., www.example.com).

Content-Type: Indicates the media type of the request body (e.g., application/json).

Authorization: Contains credentials for authenticating the request.

Accept: Specifies the media types that are acceptable for the response.

User-Agent: Provides information about the client software making the request.

Q3. What is Request Body?

The request body is the part of the HTTP request that contains the actual data being sent to the server. It is typically used with methods like POST, PUT, and PATCH to send data such as JSON, XML, or form data to the server. The structure and content of the request body depend on the Content-Type specified in the request header.

Q4. What is Response Body?

The response body is the part of the HTTP response that contains the data returned by the server to the client. This data can be in various formats, such as HTML, JSON, or XML, depending on the Content-Type specified in the response header. The response body holds the content that was requested by the client, like the result of a database query, a generated HTML page, or any other data.

Q5. What are HTTP Status Codes?

HTTP status codes are standard codes that indicate the result of the HTTP request. They help to understand whether the request was successful or if there was an error. Some common HTTP status codes include:

200 OK: The request has succeeded.

201 Created: The request has succeeded, and a new resource has been created.

204 No Content: The request has succeeded, but there is no content to return.

400 Bad Request: The server could not understand the request due to invalid syntax.

401 Unauthorized: The client must authenticate itself to get the requested response.

403 Forbidden: The client does not have access rights to the content.

404 Not Found: The server cannot find the requested resource.

500 Internal Server Error: The server encountered an unexpected condition.

Q6. How to provide an alias name for Web API Action?

You can provide an alias name for a Web API action using the [ActionName] attribute. This attribute allows you to specify a different name for the action method, which can be useful for making the API endpoints more user-friendly or consistent. For example:

public class MyController : ApiController

{

    [HttpGet]

    [ActionName("GetProductDetails")]

    public IHttpActionResult GetProductById(int id)

    {

        var product = GetProduct(id);

        if (product == null)

        {

            return NotFound();

        }

        return Ok(product);

    }

}

Q7. What is Parameter Binding in ASP.NET Web API?

Parameter binding in ASP.NET Web API is the process of setting the values of action method parameters from various parts of the HTTP request. This can include the URI, query string, request headers, and request body. ASP.NET Web API uses a combination of convention-based and attribute-based binding to map request data to action method parameters.

Q8. What is FromUri Attribute and How to use FromUri Attribute in ASP.NET Web API?

The [FromUri] attribute in ASP.NET Web API is used to specify that a parameter should be bound from the URI of the HTTP request. This includes binding data from the query string or route data. This attribute is particularly useful for simple types and complex types that are passed as part of the URL.

Example usage:

public class ProductsController : ApiController

{

    [HttpGet]

    public IHttpActionResult GetProduct([FromUri] int id)

    {

        var product = GetProductById(id);

        if (product == null)

        {

            return NotFound();

        }

        return Ok(product);

    }

    [HttpGet]

    public IHttpActionResult SearchProducts([FromUri] ProductSearchCriteria criteria)

    {

        var products = SearchProducts(criteria);

        return Ok(products);

    }

}

public class ProductSearchCriteria

{

    public string Name { get; set; }

    public decimal? MinPrice { get; set; }

    public decimal? MaxPrice { get; set; }

}

In the above example, the id parameter in the GetProduct action and the criteria parameter in the SearchProducts action are populated from the URI. The ProductSearchCriteria class properties can be bound from the query string parameters.

Q9. What is FromBody Attribute and How to use this Attribute in ASP.NET Web API?

The [FromBody] attribute in ASP.NET Web API is used to specify that a parameter should be bound from the body of the HTTP request. This attribute is typically used for complex types that are sent as JSON, XML, or other formats in the request body.

Example usage:

public class ProductsController : ApiController

{

    [HttpPost]

    public IHttpActionResult CreateProduct([FromBody] Product product)

    {

        if (product == null)

        {

            return BadRequest("Product cannot be null");

        }

        // Logic to save the product

        SaveProduct(product);

        return Ok(product);

    }

}

In this example, the product parameter is populated from the JSON data in the request body.

Q10. Can we declare FromBody attribute on multiple parameters?

No, you cannot use the [FromBody] attribute on more than one parameter in a single action method. The reason for this limitation is that the request body can only be read once, so multiple parameters cannot be bound from the body.

Q13.How to get Data from the SQL Server Database using ASP.NET Web API?

To get data from SQL Server using ASP.NET Web API, you can use Entity Framework or ADO.NET. Here is an example using Entity Framework:

1. Create a model:

public class Product

{

    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

}

2. Create a DbContext:

public class ProductContext : DbContext

{

    public DbSet<Product> Products { get; set; }

}

3. Create a controller:

public class ProductsController : ApiController

{

    private ProductContext db = new ProductContext();

    [HttpGet]

    public IEnumerable<Product> GetProducts()

    {

        return db.Products.ToList();

    }

    [HttpGet]

    public IHttpActionResult GetProduct(int id)

    {

        var product = db.Products.Find(id);

        if (product == null)

        {

            return NotFound();

        }

        return Ok(product);

    }

}

Q14.How to Post Data in ASP.NET Web API?

To post data using ASP.NET Web API, you typically use the POST method. Here is an example:

public class ProductsController : ApiController

{

    private ProductContext db = new ProductContext();

    [HttpPost]

    public IHttpActionResult CreateProduct([FromBody] Product product)

    {

        if (!ModelState.IsValid)

        {

            return BadRequest(ModelState);

        }

        db.Products.Add(product);

        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);

    }

}

Q15.How to Put or Update Data in ASP.NET Web API?

To update data using ASP.NET Web API, you typically use the PUT method. Here is an example:

public class ProductsController : ApiController

{

    private ProductContext db = new ProductContext();

    [HttpPut]

    public IHttpActionResult UpdateProduct(int id, [FromBody] Product product)

    {

        if (!ModelState.IsValid)

        {

            return BadRequest(ModelState);

        }

        if (id != product.Id)

        {

            return BadRequest();

        }

        db.Entry(product).State = EntityState.Modified;

        try

        {

            db.SaveChanges();

        }

        catch (DbUpdateConcurrencyException)

        {

            if (!ProductExists(id))

            {

                return NotFound();

            }

            else

            {

                throw;

            }

        }

        return StatusCode(HttpStatusCode.NoContent);

    }

    private bool ProductExists(int id)

    {

        return db.Products.Count(e => e.Id == id) > 0;

    }

}

Q16.How to Delete Data in ASP.NET Web API?

To delete data using ASP.NET Web API, you typically use the DELETE method. Here is an example:

public class ProductsController : ApiController

{

    private ProductContext db = new ProductContext();

    [HttpDelete]

    public IHttpActionResult DeleteProduct(int id)

    {

        var product = db.Products.Find(id);

        if (product == null)

        {

            return NotFound();

        }

        db.Products.Remove(product);

        db.SaveChanges();

        return Ok(product);

    }

}

In this example, the DeleteProduct method finds the product by its ID, removes it from the database, and saves the changes.

 



Top