簡體   English   中英

ASP.NET Core 在 Razorpages 上聲明空處理

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

我想知道處理聲明的空值檢查的最干凈的方法是什么? 現在我的頁面看起來被所有的空檢查污染了,我已經在使用自定義擴展和聲明

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 處理程序上不斷使用它。

有沒有辦法讓它更短或省略它?

您可以創建一個具有這些檢查的Custom Attribute ,然后用它裝飾 ActionResult。 或者,您可以創建Filters

如果您想了解有關Custom Attributes更多信息,請查看此文檔: https : //docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes

如果您想了解有關Filters更多信息,請查看此文檔: https : //docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters? view = aspnetcore- 2.2

整個想法是有這樣的東西:

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

然后

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM