Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET核心声明Razorpages上的空处理_C#_Asp.net Core - Fatal编程技术网

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(){…}

哦,有趣的是,我没有想到这一点。我喜欢属性方法。谢谢