【问题标题】:The resource cannot be found when following the WebAPI tutorial [duplicate]遵循WebAPI教程时找不到资源[重复]
【发布时间】:2017-02-24 08:49:34
【问题描述】:

我有 ASP.NET MVC 项目。我需要给它添加 WebAPI。

我尝试在本教程中添加模型和控制器 (https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api)

我添加了模型:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

这是我的控制器

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SmartSolutions.Models;

namespace SmartSolutions.Controllers
{
    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 }
        };
        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 class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

当我启动应用程序时,我有这个

我的错误可能在哪里?

【问题讨论】:

  • WebApiConfig 中的代码是否被调用?
  • 你说的是 Global.asax.cs?@PatrickHofman

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

如果 id 是可选的,您必须在 API 控制器的方法中将 int 作为可空值传递,并且 URL 应该是 api/products/GetProduct 也应该是访问链接,您可能会遇到已经提出的问题中提到的任何错误 Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} 它的答案类似于将您的特定规则置于一般规则之前(如默认),这意味着首先使用 RouteTable.Routes.MapHttpRoute 映射“WithActionApi”,然后映射“DefaultApi”。

 public IHttpActionResult GetProduct(int? id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    相关资源
    最近更新 更多