我试图在ASP.NET中创建一个简单的WebAPI。我把它放在IIS中。当我尝试浏览网站时,一切都很好:
但是当我尝试从API获得结果时,我收到此错误:
控制器:
public class ProductController : 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<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
WebApiConfig:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
答案 0 :(得分:2)
您在/api
访问的应用程序上托管它,因此您需要额外的/api
来匹配路由:
http://localhost:6060/api/api/Product
如果您不想这样,那么请为api
网站提供更合理的名称,从路线中移除api/
,或两者兼而有之。