While building projects in MVC we also have a requirement to build API that can run on any device whether its a mobile device or whether it is a laptop.
Web API is mainly build so that it can run on any device and on any platform. The request and response needs to be identified.

So for building Web API in MVC first step is to create project with selecting WebAPI type of project.

After that we will first add a controller named Product in which we will define the attributes and response needs to be passed while the API is called.
public class ProductModel
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class ProductResponse
{
public List<ProductModel> ProductList { get; set; }
public bool Status { get; set; }
public string Message { get; set; }
}
After that we will make the repository that will contain the method for fetching the product details from the database.
public class ProductRepository
{
#region "==== Connection String ===="
private String ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
#endregion
public ProductResponse GetProduct()
{
List<ProductModel> lstModel = new List<ProductModel>();
ProductResponse ProductResponse = new ProductResponse();
try
{
SqlDataReader reader = null;
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
{
if (sqlConnection.State == ConnectionState.Closed)
{
sqlConnection.Open();
}
reader = SqlHelper.ExecuteReader(sqlConnection, CommandType.StoredProcedure, "uspGetNudgeLocations");
if (reader.HasRows)
{
while (reader.Read())
{
lstModel.Add(new ProductModel
{
Id = reader["ProductId"] != null ? !string.IsNullOrEmpty(Convert.ToString(reader["ProductId"])) ? Convert.ToInt32(Convert.ToString(reader["ProductId"]).Trim()) : 0 : 0,
ProductName = reader["ProductName"] != null ? Convert.ToString(reader["ProductName"]).Trim() : string.Empty
});
}
}
else
{
lstModel.Add(new ProductModel
{
ProductName = "No Product Found"
});
}
}
ProductResponse.ProductList = lstModel;
ProductResponse.Status = true;
}
catch (Exception ex)
{
ProductResponse.Message = ex.Message;
ProductResponse.Status = false;
}
return ProductResponse;
}
}
Then after doing this at last we will made the controller for defining and calling this repository method into it.
public class ProductController : ApiController
{
ProductRepository ProdRepo = new ProductRepository();
public IHttpActionResult GetProduct()
{
var product = ProdRepo.GetProduct();
if (!product.Status)
{
return NotFound();
}
return Ok(product);
}
}
0 Comment(s)