如果Controller中有过滤条件,则C#mvc 5退出

时间:2018-05-01 05:14:27

标签: c# .net asp.net-mvc

我试图干掉我的代码。我有一个控制器一遍又一遍地重复相同的代码,但我不能移动到新方法,因为重复的代码包含一个return语句。

这是一个代码示例

    public class ExampleController : Controller
{

    private Authorizer _authorizer = new Authorizer();

    public ActionResult Edit(int id)
    {
//Repeated Code Start
        var result = _authorizer.EditThing(id);
        if (result.CanEditPartA)
        {
            //log attempted bad access
            //Other repeted things 
            return View("error", result.Message);
        }
//Repeated Code End 

        //unique logic to this action. 
        return View();
    }
    public ActionResult Edit1(int id, FormCollection collection)
    {
//Repeated Code Start
        var result = _authorizer.EditThing(id);
        if (result.CanEditPartA)
        {
            //log attempted bad access
            //Other repeted things 
            return View("error", result.Message);
        }
//Repeated Code End
        //unique logic to this action.

        try
        {

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

public class Authorizer
{
    // check a bunch of things and determine if person can to something

    public Result EditThing(int thingID)
    {
        //get thing from DB
        //logic of thing compared to current user
        //Create Result basied on bussness Logic
        return new Result();
    }


    public class Result
    {
        public bool CanEditPartA { get; set; }
        public bool CanEditPartB { get; set; }
        public bool CanEditPartC { get; set; }
        public string Message { get; set; }
    }
}

}

这个例子在我的实际问题中缩短了相当多的重复代码

 var result = _authorizer.EditThing(id);
        if (result.CanEditPartA)
        {
            //log attempted bad access
            //Other repeted things 
            return View("error", result.Message);
        }

我希望能够做到这样的事情

       public ActionResult Edit(int id)
    {

        if (CanUserEditPartA(id) != null)
        {
            return CanUserEditPartA(id);
        }

        //unique logic to this action. 
        return View();
    }

    private ActionResult CanUserEditPartA(int id)
    {
        var result = _authorizer.EditThing(id);
        if (result.CanEditPartA)
        {
            //log attempted bad access
            //Other repeted things 
            return View("error", result.Message);
        }
        return null;
    }

但问题是我返回null。方法编辑也退出。

有没有办法让一个辅助方法在一个路径中的某些路径中返回一个ActionResult但是如果为null或其他情况允许在主路径上继续?

1 个答案:

答案 0 :(得分:1)

这是一个使用ActionFilter的合适位置,通过正确应用它,您甚至不需要检查控制器内部操作,如果过滤器没有通过要求,那么它将设置响应和控制器操作不会在第一时间被调用。

这是一个可以帮助您的链接:https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs