c# - WebAPI 部署到 IIS,给出 404 Not Found

标签 c# asp.net asp.net-web-api iis-10

我正在尝试在 ASP.NET 中创建一个简单的 WebAPI。我把它放在IIS里了。当我尝试浏览该网站时,一切都很好:

enter image description here

但是当我尝试从 API 获取结果时,出现此错误:

enter image description here

Controller :

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);
        }
    }

WebApi配置:

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/,或者两者兼而有之。

关于c# - WebAPI 部署到 IIS,给出 404 Not Found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37275235/

相关文章:

c# - 我如何(通常)接受任何控件并设置它的 Text 属性(如果有)?

c# - WPF - 扩展器中的滚动列表框

c# - 如何从内容页使用母版页中的方法

iphone - 支持所有移动平台和 .net Web 应用程序的聊天功能框架

c# - 是否有可能无法从任务延续中触发 AppDomain 的未处理异常处理程序?

c# - 根据下拉选择 c# 填充 Listview

wcf - 何时使用MVC4 Web-API和传统的HTTP Web服务?

c# - ASP.NET Web API 序列化 JSON 错误 : "Self Referencing loop"

asp.net-web-api - 单元测试 WebApi2 传递 header 值

c# - 在返回 WCF 流的同时流式传输到文件?