DefaultControllerFactory如何处理内容请求

时间:2012-02-03 18:41:13

标签: c# asp.net-mvc-3 unity-container

我正在使用ASP.Net MVC 3框架,我正在将依赖注入集成到应用程序中。我正在尝试创建一个自定义控制器工厂。我现在遇到的最大问题是我的IControllerFactory.CreateController实现获取了诸如css,javascript和其他内容文件之类的请求,这些文件随后会导致它抛出异常作为“Scripts / html5.js”的类型不存在。代码是继承给我的,所以除了你对这个非常随意的状态的任何批评。以下是实施:

    public virtual IController CreateController(RequestContext requestContext, string controllerName)
    {
        if (requestContext == null)
        {
            throw new ArgumentNullException("requestContext");
        }

        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Value cannot be null or empty", "controllerName");
        }

        this.RequestContext = requestContext;
        try
        {
            return container.Resolve<IController>(controllerName.ToLower());
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.Message);
            return innerFactory.CreateController(requestContext, controllerName);
        }
    }

2 个答案:

答案 0 :(得分:1)

我能够通过继承DefaultControllerFactory而不是完整地实现IControllerFactory来解决这个问题:

public class MyControllerFactory : DefaultControllerFactory

然后我只需要覆盖GetControllerInstance方法来挂钩并从我的Unity容器中返回任何实例:

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        IController controller = null;
        if (controllerType == null)
        {
            throw new HttpException(404, String.Format("The controller for path '{0}' could not be found or it does not implement IController.", requestContext.HttpContext.Request.Path));
        }

        if (!typeof(IController).IsAssignableFrom(controllerType))
        {
            throw new ArgumentException(String.Format("Type requested is not a controller: {0}", controllerType.Name), "controllerType");
        }

        try
        {
            if (this.container.IsRegistered(controllerType))
            {
                controller = this.container.Resolve(controllerType) as IController;
            }
            else
            {
                controller = base.GetControllerInstance(requestContext, controllerType);
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(String.Format("Error resolving controller {0}", controllerType.Name, ex));
        }

        return controller;
    }

答案 1 :(得分:0)

您可以尝试以下几种方法:

routes.IgnoreRoute("{file}.css"); //plus others if you have specifics

或更好,只需尝试

routes.RouteExistingFiles = false;