Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

In asp.net mvc is it possible to make a generic controller?

I'm attempting to create a generic controller, ie:

public class MyController<T> : Controller where T : SomeType
{ ... }

However, when I try to use it, I'm running into this error everywhere...

Controller name must end in 'Controller'

So, my question, Is it possible to make a generic controller in asp.net mvc?

Thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If I understand you properly, what you are trying to do, is route all requests for a given Model through a generic controller of type T.

You would like the T to vary based on the Model requested.

You would like /Product/Index to trigger MyController<Product>.Index()

This can be accomplished by writing your own IControllerFactory and implementing the CreateController method like this:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    Type controllerType = Type.GetType("MyController")
                              .MakeGenericType(Type.GetType(controllerName));
    return Activator.CreateInstance(controllerType) as IController;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...