C# 参数的可空快捷方式或扩展名
下面这行代码我重复了无数次,也有类似的代码C# 参数的可空快捷方式或扩展名,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,下面这行代码我重复了无数次,也有类似的代码 public ActionResult View(int ? id) { if (id.HasValue == false) { return HttpNotFound(); } ..... } 如何将其缩短?您可以为其创建一个属性。我可能看起来像这样: 属性 public class NullableValidatorAttribute
public ActionResult View(int ? id)
{
if (id.HasValue == false)
{
return HttpNotFound();
}
.....
}
如何将其缩短?您可以为其创建一个属性。我可能看起来像这样: 属性
public class NullableValidatorAttribute : ActionFilterAttribute
{
protected String[] ParametersNames { get; set; }
public String HttpNotFoundStatusDescription { get; set; }
public NullableValidatorAttribute(params String[] parametersNames)
{
if (parametersNames == null)
throw new ArgumentNullException("parametersNames");
ParametersNames = parametersNames;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parametersNames = new HashSet<String>(ParametersNames);
foreach (var parameterName in parametersNames)
{
var parameterValue = filterContext.ActionParameters[parameterName];
if (parameterValue == null)
{
filterContext.Result = new HttpNotFoundResult(HttpNotFoundStatusDescription);
return;
}
}
base.OnActionExecuting(filterContext);
}
}
以上只是一个原始实现。例如,您可以从构造函数中删除参数的名称,并解析任何操作参数(通过反射或其他方式获取参数类型),等等。这是两行代码,我不认为将其减少到一行可以保证额外的肤色层。我不认为在这种情况下,
HttpNotFound
是正确的状态。有什么更好的方法吗?您可以尝试编写操作过滤器,因为它可以缩短视图的渲染。。。不确定它是否更紧凑/可读。。。
[NullableValidator("id", "id2", HttpNotFoundStatusDescription = "some description")]
public ViewResult Test(int? id, int? id2)
{
return View();
}