【问题标题】:using Web Api in Webforms return 404 error在 Webforms 中使用 Web Api 返回 404 错误
【发布时间】: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


    【解决方案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?.

    【讨论】:

    • 我应该在哪里添加控制器类?
    • 没关系。大多数人只是创建一个名为Controllers 的文件夹并将它们放在那里。一旦类被包含在项目中
    • 它没有用。我添加了所有属性并更新了 global.asax 文件。我创建了一个启用了 Web api 的新 webforms 项目。 Web api 控制器在那里工作正常。我正在考虑将 tis 项目中的所有文件复制到该项目中。
    • 你也可以这样做。我认为这没有错。我建议您查看新项目与当前项目的差异,以便了解可能导致问题的原因。编码愉快。
    • 看看下面对Can you use the attribute-based routing of WebApi 2 with WebForms?的回答。我已更新我的答案以包含其他信息。
    【解决方案2】:

    根据您的代码,您没有包含 webapi 的路由。如果您从 Nuget 安装 Webapi,您可以在 App_Start 下找到 WebApiConfig 文件,其中包含 WebApi 的 Route 配置。 如果不为 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);
        }
    

    【讨论】:

    • 我做了所有这些,仍然是同样的问题。我需要更改 web.config 中的任何内容吗?
    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2020-10-20
    • 2013-05-21
    • 1970-01-01
    • 2015-08-08
    • 2019-09-09
    相关资源
    最近更新 更多