我怎样才能改变控制器在Asp.NET MVC命名约定? [英] How can I change the Controller Naming Conventions in Asp.NET MVC?

查看:137
本文介绍了我怎样才能改变控制器在Asp.NET MVC命名约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在asp.NET MVC开发。我有一个要求分开查看项目的Web API,我想的WebAPI控制器具有查看项目不同的命名约定,很容易识别什么是什么是视图控制器的WebAPI控制器。在这两个项目中,默认的约定是名称+'控制'。如果是要改变它的WebAPI,例如一种方式,而不是'WebAPiController这将是很好的,我想要的名称惯例是WebAPICtrl瓯WebAPiService。

I'm starting to develop in asp.NET MVC. I have a requirement to separate a Web API from View projects, I want WebAPI controllers to have different naming conventions from View project, to easily identify what is webapi controller from what is a controller for view. In both projects, the default convention is name + 'Controller'. It would be nice if there're a way to change it in webapi, example, instead of 'WebAPiController', I want the name convention to be 'WebAPICtrl' ou 'WebAPiService'.

这是我发现它很接近了这样的问题:
<一href=\"http://stackoverflow.com/questions/3011482/change-controller-name-convention-in-asp-net-mvc/30577420?noredirect=1#comment49228286_30577420\">change在ASP.NET MVC 控制器名称约定

The question that I found it's close is: change controller name convention in ASP.NET MVC

我怎么能在Asp.net存档这一要求MVC 5?

How can I archive this requirement in Asp.net mvc 5?

推荐答案

在Global.asax中内你的Application_Start()方法,你就需要更换ControllerBuilder.Current到控制器工厂的自定义实现。

In your Application_Start() method inside of Global.asax, you would need to replace the ControllerBuilder.Current to a custom implementation of controller factory.

 public class MvcApplication : HttpApplication
{

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        var controllerFactory = new CustomControllerFacotry();
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }
}

您将需要一个类从DefaultControllerFactory继承和超越您的自定义实现CreateController方法。请看看关于如何做到这一点的进一步指导的默认实现。这将是这个样子。

You'll need to a class to inherit from DefaultControllerFactory and override the CreateController method with your custom implementation. Please look at the default implementation for further guidance on how to do this. It would look something like this.

public class CustomControllerFactory : DefaultControllerFactory
{
     public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        string controllername = requestContext.RouteData.Values["controller"].ToString();       
        Type controllerType = Type.GetType(string.Format("Namespace.{0}",controllername));
        IController controller = Activator.CreateInstance(controllerType) as IController;
        return controller;

    }
}

这篇关于我怎样才能改变控制器在Asp.NET MVC命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆