来自其他类库的基本控制器在Web API中不起作用

用户1019872

我有两个Web API项目,并且有一个MarketController,我需要扩展Api控制器,所以做到了。

我创建了一个BaseController类并从中继承ApiController

public class BaseController:ApiController { }

到目前为止,一切正常,它工作正常:

public class MarketController : BaseController
{
    public MarketController() : base()
    {
    }

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

但是我想在另一个名为的类库中进行操作BLL,因此我将该BaseController类移至该BLL类库,并在Web API项目中对其进行了引用。

当我这样做时,api停止工作。

响应为:

{
    "Message": "No HTTP resource was found that matches the request URI someurl/api/market.",
    "MessageDetail": "No type was found that matches the controller named 'market'."
}
阿杰·凯卡(Ajay Kelkar)

默认情况下,MVC在mvc应用程序的同一程序集中查找所有控制器。默认的控制器工厂会基于字符串'ControllerName + Controller'创建控制器实例,例如MarketController,其中market来自URL market / actionname,它将在与mvc应用程序相同的程序集中查找MarketController。

要将控制器放在单独的程序集中,您将必须创建自己的控制器工厂,或者必须将程序集名称指定为app start。

创建自己的自定义ControllerFactory后,请将以下行添加到global.asax的Application_Start中,以告诉框架在哪里找到它:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

或者对于像您这样的简单情况,您可以执行以下操作:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" },
    new[] { "BLLAssembly.Controllers" }
);

在这里,BLLAssembly.Controllers是BLL程序集中BaseController的命名空间。

使用自定义程序集解析器还有一种更高级的方法,即IAssembliesResolver下面的文章介绍了如何使用Web Api进行此操作,

http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章