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

标签 c# generics asp.net-web-api autofac

我正在尝试在我的 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/

相关文章:

java - 如何满足参数类型Class<?在java中扩展someInterface>

c# - 如何使用 HttpClient 类正确建立从 UWP App 到 WebAPI 的 SSL 连接?

list - Web API 使用附加属性扩展列表

c# - 具有通用类型的 MS CRM 自定义工作流事件输出

c# - 创建用于创建网页的脚本语言

c# - 如何在 C# 中正确设计通用 "request dispatcher"

java - 将类更改为泛型类型

c# - 从 ASP.NET Web API 返回 HTML

c# - 何时加载 Generic.xaml 样式?

c# - 带有 Dbcontext 的 ExecuteStoreQuery