Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

change controller name convention in ASP.NET MVC

Is there a way to change the naming convention for controllers in ASP.NET MVC?

What I want is to name my controllers InicioControlador instead of InicioController, or better yet, use a prefix instead of a suffix, and have ControladorInicio as my controller name.

From what I have read so far, I think I have to implement my own Controller Factory. I would be very grateful if any of you could point me in the right direction.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I decided to dig a bit deeper and found exactly what I was looking for after searching through the MVC source code. The convention for controller names is deep inside the roots of the MVC Framework, especifically in two classes ControllerDescriptor and ControllerTypeCache.

In ControllerDescriptor it is given by the following attribute:

public virtual string ControllerName {
  get {
    string typeName = ControllerType.Name;
    if (typeName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) {
      return typeName.Substring(0, typeName.Length - "Controller".Length);
    }
    return typeName;
  }
}

In ControllerTypeCache it is given by the following methods:

internal static bool IsControllerType(Type t) {
  return
    t != null &&
    t.IsPublic &&
    t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&
    !t.IsAbstract &&
    typeof(IController).IsAssignableFrom(t);
}

public void EnsureInitialized(IBuildManager buildManager)
{
  if (_cache == null)
  {
    lock (_lockObj)
    {
      if (_cache == null)
      {
        List<Type> controllerTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(_typeCacheName, IsControllerType, buildManager);
        var groupedByName = controllerTypes.GroupBy(
            t => t.Name.Substring(0, t.Name.Length - "Controller".Length),
            StringComparer.OrdinalIgnoreCase);
        _cache = groupedByName.ToDictionary(
            g => g.Key,
            g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),
            StringComparer.OrdinalIgnoreCase);
      }
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...