Welcome 微信登录

首页 / 网页编程 / ASP.NET / Asp.net MVC示例项目“Suteki.Shop”分析之Controller

Asp.net MVC示例项目“Suteki.Shop”分析之Controller2009-12-31 博客园 代震军在上文中,介绍了如何安装和使用Suteki,今天我们通过源码来看一下Suteki是如何使用Controller 。

在Suteki中,其使用Abstract的方式来定义一个ControllerBase,以此作为所有Controller的 基类,下面是其Controller的类设计图:

在该基类中定义了一些Controller中常用到的方法,比如为当前视图添加MetaDescription,Title等 :

[Rescue("Default"), Authenticate, CopyMessageFromTempDataToViewData]
public abstract class ControllerBase : Controller, IProvidesBaseService
{
private IBaseControllerService baseControllerService;

/// <summary>
/// Supplies services and configuration to all controllers
/// </summary>
public IBaseControllerService BaseControllerService
{
get { return baseControllerService; }
set
{
baseControllerService = value;

ViewData["Title"] = "{0}{1} ".With(
baseControllerService.ShopName,
GetControllerName());

ViewData["MetaDescription"] = ""{0}"".With (baseControllerService.MetaDescription);
}
}

public ILogger Logger { get; set; }

public virtual string GetControllerName()
{
return " - {0}".With(GetType().Name.Replace("Controller", ""));
}


public virtual void AppendTitle(string text)
{
ViewData ["Title"] = "{0} - {1}".With(ViewData["Title"], text);
}

public virtual void AppendMetaDescription(string text)
{
ViewData ["MetaDescription"] = text;
}

public string Message
{
get { return TempData["message"] as string; }
set { TempData ["message"] = value; }
}

protected override void OnException (ExceptionContext filterContext) {
Response.Clear();
base.OnException (filterContext);
}
}

当然,细心的朋友发现了该抽象类中还包括一个 IBaseControllerService接口实例。

该接口的主要定义了一些网店系统信息,如店铺名称,版权 信息,Email信息等,如下:

public interface IBaseControllerService
{
IRepository<Category> CategoryRepository { get; }
string GoogleTrackingCode { get; set; }
string ShopName { get; set; }
string EmailAddress { get; set; }
string SiteUrl { get; }
string MetaDescription { get; set; }
string Copyright { get; set; }
string PhoneNumber { get; set; }
string SiteCss { get; set; }
}

而作为唯一一个实现了该接口的子类“BaseControllerService”定义如下:

public class BaseControllerService : IBaseControllerService
{
public IRepository<Category> CategoryRepository { get; private set; }
public string GoogleTrackingCode { get; set; }
public string MetaDescription { get; set; }
private string shopName;
private string emailAddress;
private string copyright;
private string phoneNumber;
private string siteCss;

..
}