1

I have a ASP.NET MVC 4 project, which have main page, where visitor should choose subtopic. So structure is:

sypalo.com
photo.sypalo.com
seo.sypalo.com
... and so on

I'm using AttributeRouting.net nuget package to deal with routing to subdomains. So each controller located in separate area and have following data annotation (SEOController in this case):

[RouteArea("SEO", Subdomain = "seo")]
public class SEOController : Controller
{
    private IPostRepository PostRepository;

    public SEOController()
    { this.PostRepository = new PostRepository(new BlogEntities()); }

    public SEOController(IPostRepository PostRepository) 
    { this.PostRepository = PostRepository; }

    [GET("{page?}")]
    public ActionResult Index(int? page)
    { return View(PostRepository.GetPosts("SEO", page ?? 1)); }

    [GET("{year}/{month}/{link}")]
    public ActionResult Details(int year, int month, string link)
    {
        Post post = PostRepository.GetPost("SEO", link);
        if (post == null) return HttpNotFound();
        return View(post.Text.Replace(ViewRes.Main.ReadMore, ""));
    }
}

I'm implemented repository to decrease amount of duplicated code, but still need to have controller with CRUD actions for each subdomain. All of them using single table wich have separate field called subdomain and I'm passing subdomain name statically in each controller.

I'm looking how to create base controller class with CRUD functionality anв possibility to extend it in derived classes, as each subdomain will have each own actions/views as well. AFAIK I can specify location of View or SharedView to have single view which used by multiple controllers (single Index/Details/Edit View) and pass page title and other tags in ViewBag to avoid maintaining same code for different subdomains, but I'll be much appreciated if someone will suggest better approach.

4

1 回答 1

1

You could do it something like this

public abstract class MyBaseController : Controller
{
    public virtual void Create() 
    {
        //standard implementation
    }
}

public class SEOController : MyBaseController 
{
    public override void Create()
    {
        //specific to SEO
    }
 }

You would just override what you needed to be specific to your SEOController, everything else you could just use the default MyBaseController methods.

Would probably want to move your PostRepository and stuff to the base controller as well if other classes also need them, but I don't know enough about your implementation to say for sure if that's what you would wanna do.

于 2013-10-24T15:01:09.100 回答