gpt4 book ai didi

c# - 当类是通用的时找不到 Web API Controller

转载 作者:行者123 更新时间:2023-11-30 21:37:46 24 4
gpt4 key购买 nike

我正在尝试在我的 Web API 中使用通用 Controller 。我目前未能实现的目标是从我的前端传入一个对象,该对象将显示一个 typeId。基于这个 typeId,我打算使用工厂来注入(inject)通用接口(interface)的正确类实现。我相信我的工厂、接口(interface)和服务是正确的,但出于某种原因,当我向 API 添加通用时,我得到了 404。它没有通用,只是一个测试方法。我正在使用 autofac 进行 IoC 注册。

API Controller :

public class ListItemsController<T> : ApiControllerBase
{
private readonly IListItemsService<T> _service;

public ListItemsController(int listItemTypeId)
{
_service = ListItemsFactory<T>.InitializeService(listItemTypeId);
}

[HttpGet]
[Route("{listItemTypeId: int}")]
public IEnumerable<T> GetAll()
{
return _service.GetAll();
}

[HttpGet]
[Route("test")]
public IHttpActionResult Test()
{
return Ok();
}
}

工厂:

public class ListItemsFactory<T>
{
public ListItemsFactory(IPrimaryContext context) : base()
{
}

public static IListItemsService<T> InitializeService(int listItemType)
{
switch (listItemType)
{
case 1: return (IListItemsService<T>)
new FloorTypeService(new PrimaryContext());
default: return null;
}
}
}

接口(interface):

public interface IListItemsService<T>
{
IEnumerable<T> GetAll();
void Save(T obj);
T GetById(int id);
void Delete(int id);
}

错误:

No HTTP resource was found that matches the request URI 'http://localhost:9000/api/v1/listitems/test'. No type was found that matches the controller named 'listitems'.

我不确定我在这里遗漏了什么。我正在使用路由属性,但这是我的 API 配置:

private static void SetupRoutes(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
config.Routes.MapHttpRoute("DefaultApi", "api/v{version}/{controller}/{id}",
new { id = RouteParameter.Optional });
}

最佳答案

除了解析类型并尝试映射到正确的 Controller 之外,您还可以为每个类型创建一个 Controller ,它继承自您的 GenericController。然后就不用copy代码了,每个Type都有一个Controller,可以通过RouteAttribute路由到:

public class ListItemsController<T> : ApiControllerBase
{
//Properties/Fields should be protected to can be accessed from InstanceController.
protected readonly IListItemsService<T> _service;
// I think listItemTypeId is not necessary, if generic-type T is used?
public ListItemsController()
{
_service = ListItemsFactory<T>.InitializeService();
}

[HttpGet] // No need for RouteAttribute, because it will be in InstanceController.
public IEnumerable<T> GetAll()
{
return _service.GetAll();
}

[HttpGet]
[Route("test")] // This can rest here, because you want to use it.
public IHttpActionResult Test()
{
return Ok();
}



}

实现的 InstanceController 看起来像这样:

[RoutePrefix("api/{controller}")]
public class FloorItemsController ListItemsController<Floor>
{
// delegate the Constructor-call to base()
public ListItemsController()
:base()
{

}

// No need to reimplement Methods.
}

RouteConfiguration 应该设置回默认值,因为 RouteAttributes 是为此设置的。

关于c# - 当类是通用的时找不到 Web API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com