【发布时间】:2016-03-26 18:13:11
【问题描述】:
我有一个包含 Web API 的 ASP.NET Webforms 网站。该网站是在 Windows 8 上使用 Visual Studio 2013 和 .NET 4.5 开发和测试的,并使用 IIS Express 作为 Web 服务器。
我在根目录下添加了Web Api控制器,定义如下:
[RoutePrefix("api")]
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 }
};
[Route("ProductsController")]
[HttpGet]
public IEnumerable<Product> 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<Product> GetProductsByCategory(string category)
{
return products.Where(
(p) => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
}
Global.asax 看起来像这样:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
}
}
我已将这两行包含在我的 web.config 文件中
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
当我使用以下 URL 发出 get 请求时:http://localhost:5958/api/products,我收到 HTTP 错误 404.0。我尝试了不同的解决方案,但没有任何效果。有什么我想念的吗?我该如何解决这个问题?
提前致谢。
【问题讨论】:
标签: asp.net asp.net-web-api webforms asp.net-web-api2