Skip to main content
 首页 » 编程设计

c#之在基本 Controller MVC 中实现逻辑

2024年02月05日16jirigala

在我的 Controller 中的每个操作中,我使用以下代码:

    public async System.Threading.Tasks.Task<ActionResult> Details(string source, string id) 
    { 
        var max = Helpers.GetSource(source); 
        if (max == null) 
            return Content("Please check your request URL format, there is no source defined for your input"); 
 
        using (var cmax = new CMax(max.ConnectionString)) 
        { 

我希望能够嵌入基本功能,让所有 Actions 默认采用 Source,生成一个“max”对象,并将 Action 函数的主体包装在我的 using 语句中。

是否可以将这个功能实现到基类中,这样我就不会在每个 Action 中都有这个冗余代码?

请您参考如下方法:

我发现最好的实现方法是覆盖 OnActionExecuting。

    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        _max = Helpers.GetSource(Request.QueryString["source"]); 
 
        if (_max == null) 
        { 
            filterContext.Result = 
                Content("Please check your request URL format, there is no source defined for your input"); 
            return; 
        } 
 
        base.OnActionExecuting(filterContext); 
    } 

这允许我在类级别而不是在操作级别定义_max,并在类级别再次实现检查逻辑。