【问题标题】:How to fix http error 500 regarding routing?如何修复有关路由的http错误500?
【发布时间】:2014-03-28 13:34:35
【问题描述】:

我正在使用 asp.net web api 2,请求无法定位和运行 IHttpActionResult 方法。我相信他们是我的路由问题。我得到的错误(http 500)响应是:“尝试创建类型的控制器时发生错误确保控制器具有无参数的公共构造函数。”

我发送的请求是:动词:GET localhost:xxxx/api/simpleproduct/getproduct?id=3

[RoutePrefix("api/simpleproduct")]
    public class SimpleProductController : ApiController
    {
        List<Product> products = new List<Product>() { new Product { Id = 1, Name = "Demo1", Price = 1 }, new Product { Id = 2, Name = "Demo2", Price = 2 }, new Product { Id = 3, Name = "Demo3", Price = 3 } };

        public SimpleProductController(List<Product> products)
        {
            this.products = products;
        }

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }
        [Route("getproduct")]
        [HttpGet]
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        public IHttpActionResult AddProduct(int Id, string Name, decimal Price)
        {
            if (Id == 0 || Name == null || Price == 0)
            {
                return Conflict();
            }

            products.Add(new Product { Id = Id, Name = Name, Price = Price });

            return Ok(products);
        }

        public IHttpActionResult DeleteProduct(int Id)
        {
            if (Id < 0)
            {
                return Conflict();
            }

            var products2 = products.ToList();
            foreach (var product2 in products2)
            {
                if (product2.Id == Id)
                {
                    products.Remove(product2);
                }
            }

            return Ok(products);
        }
    }

【问题讨论】:

  • 您是否尝试添加无参数构造函数?
  • 我也不确定你为什么要通过控制器传递产品,你应该只传递依赖项。
  • 我试过了,但没用。你指的是addproduct吗?

标签: c# json http asp.net-web-api asp.net-web-api2


【解决方案1】:

就像在 cmets 中已经提到的 @PmanAce,您需要一个无参数的公共构造函数。

public SimpleProductController()
{
}

我假设您只是在测试/试用 Web API,这就是您将产品硬编码为私有变量的原因。在这种情况下,您根本不需要构造函数来获取 products 参数。

如果您让示例工作,您可能想尝试将存储库注入您的控制器。它将检索数据(映射到您的实体)的逻辑与控制器分离。这是一篇关于 Web API 控制器的依赖注入的好文章,它利用存储库和 Unity 将其作为依赖注入。奇怪的是,它使用了您正在使用的相同产品结构。

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多