I'm having some troubles accessing my WebApi in an asp.net WebForms app.
I followed the Microsoft article here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms
When I access the API from Default.aspx using a client-side AJAX request using jQuery, everything works fine.
function getProducts() {
$.getJSON("api/products",
function (data) {
// Loop through the list of products.
$.each(data, function (key, val) {
var msg = 'Name: ' + val.Name + ' - Price: ' + val.Price;
alert(msg);
});
});
}
$(document).ready(getProducts);
Issue
However, when trying to access the same endpoint using Postman, all I get is the HTML for my website instead of JSON.
Question
How can I access my WebAPI using Postman?
In Global.asax.cs, Application_Start I added the following:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
In my website project, I added a new Web API Controller Class (v2.1), which was placed inside the root directory's App_Code folder.
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable GetProductsByCategory(string category)
{
return products.Where(
(p) => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
}
