为 ASP.Net MVC 站点创建 customBaseController?

在我正在处理的项目中,我发现在每个操作的开始和结束时,我都有相同的代码来检索,然后将对象存储在 TempData[] 中。所有操作之间的代码都是一致的,所以我想知道创建一个基本控制器类来执行冗余重构并将对象存储在 TempData[] 中是否合理?


有没有更聪明的方法?


我目前的代码:


public ActionResult Index(StepOne data)

{

    var customer = TempData["customer"] as Customer;


    //do stuff with customer


    TempData["customer"] =customer;


    return View();

}


UYOU
浏览 159回答 1
1回答

慕村9548890

为什么不创建一个名为 BaseController 或其他控制器的控制器,然后像下面编写的代码一样从这个 BaseController 继承其他控制器。//Your base controllerpublic class BaseController : Controller{    //This will be executed after every action call on the controllers inherited from this BaseController.    //You can use OnActionExecuting in case you want the execution before the actions execution in your other controllers.    protected override void OnActionExecuted(ActionExecutedContext filterContext)    {        Controller controller = filterContext.Controller as Controller;        if (controller != null)        {            var customer = controller.TempData["customer"] as Customer;            //do stuff with customer            controller.TempData["customer"] = customer;        }    }}//Then your other controllerpublic class HomeController : BaseController{    public ActionResult Index(StepOne data)    {        //You can get your TempData here too.        var customer = TempData["customer"] as Customer;        return View();    }}如果它不起作用或者您需要将此代码更改为某种其他类型的行为,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP