我有一个包含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 http://localhost:5958/api/products发出get请求时,我收到HTTP错误404.0。我尝试了不同的解决方案但没有任何效果有什么东西我不见了吗?我该如何纠正这个问题?
提前致谢。
答案 0 :(得分:1)
您为Web api混合了一些基于约定的属性和属性路由。
Attribute Routing in ASP.NET Web API 2
如果您要使用属性路由,则需要正确add the routes到控制器。
[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
//...code removed for brevity
//eg: GET /api/products
[HttpGet]
[Route("")]
public IEnumerable<Product> GetAllProducts(){...}
//eg: GET /api/products/2
[HttpGet]
[Route("{id:int}")]
public Product GetProductById(int id){...}
//eg: GET /api/products/categories/Toys
[HttpGet]
[Route("categories/{category}")]
public IEnumerable<Product> GetProductsByCategory(string category){...}
}
现在您已正确定义路线,您需要enable attribute routing。
WebApiConfig.cs
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Convention based routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
请务必将Global.asax
代码更新为以下内容:
public class Global : HttpApplication {
void Application_Start(object sender, EventArgs e) {
//ASP.NET WEB API CONFIG
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
WebForm的RouteConfig
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
资源:
Can you use the attribute-based routing of WebApi 2 with WebForms?
答案 1 :(得分:0)
根据您的代码,您没有包含webapi的路由。如果从Nuget安装Webapi,您可以在App_Start下找到包含WebApi的Route配置的 WebApiConfig 文件。 如果没有为webapi创建新的路由配置文件
using System.Web.Http;
public static class 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 }
);
}
}
在Global.ascx中使用此静态方法。
using System.Web.Http;
void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}