C# ASP.NET核心声明Razorpages上的空处理
我想知道处理声明的空检查最干净的方法是什么?现在我的页面看起来被所有的空检查污染了,我已经在使用自定义扩展和声明了C# ASP.NET核心声明Razorpages上的空处理,c#,asp.net-core,C#,Asp.net Core,我想知道处理声明的空检查最干净的方法是什么?现在我的页面看起来被所有的空检查污染了,我已经在使用自定义扩展和声明了 var value = User.GetUserId(); // get ClaimType.UserId if(string.IsNullOrWhiteSpace(value)) { throw new NullReferenceException(); } int userId; if(!int.TryParse(value, out userId)) { t
var value = User.GetUserId(); // get ClaimType.UserId
if(string.IsNullOrWhiteSpace(value))
{
throw new NullReferenceException();
}
int userId;
if(!int.TryParse(value, out userId))
{
throw new NullReferenceException();
}
现在如果我得到的索赔比
var value = User.GetUserId(); // get ClaimsType.UserId
var value2 = User.GetEmail(); // get ClaimsType.Email
if(string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(value2))
{
throw new NullReferenceException();
}
int userId;
if(!int.TryParse(value, out userId))
{
throw new NullReferenceException();
}
我必须经常在Get和Post处理程序中使用它
有没有办法让它保持更短或更简单?您可以创建一个带有这些检查的
自定义属性,然后用它装饰ActionResult。或者,您可以创建过滤器
如果您想了解有关自定义属性的更多信息,请查看此文档:
如果您想了解有关过滤器的更多信息,请查看此文档:
整个想法是要有这样的东西:
公共类CheckClaimsAttribute:属性
{
//你的支票在这里
}
然后
[HttpGet]
[支票索赔]
公共IActionResult MyGetMethod(){…}
[HttpPost]
[支票索赔]
public IActionResult MyPostMethod(){…}
哦,有趣的是,我没有想到这一点。我喜欢属性方法。谢谢