简体   繁体   English

ASP.NET Core 在 Razorpages 上声明空处理

[英]ASP.NET Core Claims null handling on Razorpages

I was wondering what is the most clean approach to handle null checking for claims?我想知道处理声明的空值检查的最干净的方法是什么? Right now my pages look polluted with all the null checking and i'm already using custom extensions and claims现在我的页面看起来被所有的空检查污染了,我已经在使用自定义扩展和声明

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();
}

now if i get more claims than现在如果我得到的索赔比

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();
}

and i have to use it constantly on my Get and Post handlers.我必须在我的 Get 和 Post 处理程序上不断使用它。

Is there a way to keep this shorter or ommit it?有没有办法让它更短或省略它?

You can create a Custom Attribute that has these checks then decorate the ActionResult with it.您可以创建一个具有这些检查的Custom Attribute ,然后用它装饰 ActionResult。 Or, you could create Filters .或者,您可以创建Filters

If you want to learn more about Custom Attributes , check this doc: https://docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes如果您想了解有关Custom Attributes更多信息,请查看此文档: https : //docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes

If you want to learn more about Filters , check this doc: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2如果您想了解有关Filters更多信息,请查看此文档: https : //docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters? view = aspnetcore- 2.2

The whole idea is to have something like this:整个想法是有这样的东西:

public class CheckClaimsAttribute : Attribute
{
    //your checks here
}

Then然后

[HttpGet]
[CheckClaims]
public IActionResult MyGetMethod() {...}

[HttpPost]
[CheckClaims]
public IActionResult MyPostMethod() {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM