部署到 IIS 的 WebAPI,给出 404 Not Found

WebAPI deployed to IIS, gives 404 Not Found

我正在尝试在 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 }
            );
        }

您将其托管在 /api 访问的应用程序上,因此您需要额外的 /api 来匹配路由:

http://localhost:6060/api/api/Product

如果您不希望这样,则要么给 api 站点一个更合理的名称,要么从路由中删除 api/,或者两者兼而有之。