c# - 如果控制器中的过滤条件,C# mvc 5 退出
问题描述
我试图干掉我的代码。我有一个控制器一遍又一遍地重复相同的代码,但我不能转移到新方法,因为重复的代码包含一个返回语句。
这是一个代码示例
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 或其他情况,则允许在主路径上继续?
解决方案
这是使用 ActionFilter 的合适地方,通过正确应用它,您甚至不需要检查控制器操作内部,如果过滤器没有通过要求,那么它将设置响应并且不会调用控制器操作首先。
推荐阅读
- php - MySQL INSERT 将 BIT 插入 1 而不是 0
- prolog - Prolog - 如何将原子与涉及谓词的表达式分开?
- php - php composer.json JSON 注释替代
- php - 链接的 href 动态生成不适用于 php。打印但不起作用
- java - 从 RecyclerView 适配器类调用 Activity 中的方法
- azure - PEM 证书的 Azure B2C RSA 公钥
- python - 正则表达式 - 仅当前后有空格时才拆分字符
- arrays - 如何使用 jq 从 JSON 数组中提取特定字段
- python - 包含矩阵和向量的动态列表/数组
- excel - 可以通过公式定义自定义格式(不使用VBA)