我有一个带有几个 Controller 的ASP.NET Web API(.NET 4)应用程序。我们将在IIS上运行Web API应用程序的多个实例,只是有所不同。在某些IIS实例下,只有某些 Controller 才可用。我当时想的是在实例启动时禁用/卸载不适用于该实例的 Controller 。
任何人都可以得到一些信息来指导我正确的方向吗?
最佳答案
您可以通过装饰DefaultHttpControllerActivator来放置自己的自定义IHttpControllerActivator
。在内部,只需检查设置并仅在允许的情况下创建 Controller 。
当您从Create方法返回null时,用户将收到404 Not Found消息。
我的示例显示了正在检查“应用程序设置”(App.Config或Web.Config)中的值,但显然,这可能是任何其他环境感知条件。
public class YourCustomControllerActivator : IHttpControllerActivator
{
private readonly IHttpControllerActivator _default = new DefaultHttpControllerActivator();
public YourCustomControllerActivator()
{
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
if (ConfigurationManager.AppSettings["MySetting"] == "Off")
{
//Or get clever and look for attributes on the controller in controllerDescriptor.GetCustomAttributes<>();
//Or use the contoller name controllerDescriptor.ControllerName
//This example uses the type
if (controllerType == typeof (MyController) ||
controllerType == typeof (EtcController))
{
return null;
}
}
return _default.Create(request, controllerDescriptor, controllerType);
}
}
您可以像这样切换激活器:
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new YourCustomControllerActivator());
更新
自从我看了这个问题已经有一段时间了,但是如果我今天要解决这个问题,我会稍微改变一下方法,并使用自定义的
IHttpControllerSelector
。这在激活器之前被调用,并为启用和禁用 Controller 提供了更为有效的位置...(尽管其他方法确实可行)。您应该能够装饰或继承DefaultHttpControllerSelector
。
关于asp.net-web-api - 在运行时禁用ApiController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13484826/