Dav*_*eer 1 c# record asp.net-core nullable-reference-types
感谢审稿人找到重复内容:How do I target attribute for a record class?
.NET 5.0 Web API不适用于具有所需属性的记录也与之相关。
我试图理解为什么 3. 位置记录属性在下面不起作用。
这是一个新的 ASP.NET Core Razor Pages Web 应用程序,其源代码位于https://github.com/djhmateer/record-test
https://daveabrock.com/2020/11/18/simplify-api-models-with-records似乎已经让它与 API 一起使用。
public class LoginModelNRTB : PageModel
{
[BindProperty]
// there will never be an InputModel on get
// but if we set to nullable InputModel then the cshtml will produce dereference warnings
// https://stackoverflow.com/a/54973095/26086
// so this will get rid of the warnings as we are happy we will never get dereferences on the front
// ie we are happy the underlying framework will not produce null reference exceptions
public InputModel Input { get; set; } = null!;
// 1. Original Class which works
//public class InputModel
//{
// // don't need required as Email property is non nullable
// //[Required]
// // makes sure a regex fires to be in the correct email address form
// [EmailAddress]
// // there should always be an email posted, but maybe null if js validator doesn't fire
// // we are happy the underlying framework handles it,
// public string Email { get; set; } = null!;
// // When the property is called Password we don't need a [DataType(DataType.Password)]
// //[DataType(DataType.Password)]
// public string Password { get; set; } = null!;
// [Display(Name = "Remember me?")]
// public bool RememberMe { get; set; }
//}
// 2. Record which works
//public record InputModel
//{
// [EmailAddress]
// public string Email { get; init; } = null!;
// [DataType(DataType.Password)]
// public string PasswordB { get; init; } = null!;
// [Display(Name = "Remember me?")]
// public bool RememberMe { get; init; }
//}
// 3. Positional record attributes not being picked up
public record InputModel(
string Email,
[DataType(DataType.Password)] string PasswordB,
[Display(Name = "Remember me?")] bool RememberMe);
public void OnGet() { }
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
// Input property of type InputModel is bound because of the [BindProperty] attribute
Log.Information($"Success! {Input}");
return LocalRedirect("/");
}
Log.Information($"Failure on ModelState validation {Input}");
return Page();
}
}
Run Code Online (Sandbox Code Playgroud)
从提案规范来看:
property:通过使用语法上应用于相应记录参数的属性的或field:目标,可以将属性应用于合成的自动属性及其支持字段。
接下来尝试:
public record InputModel(
string Email,
[property:DataType(DataType.Password)] string PasswordB,
[property:Display(Name = "Remember me?")] bool RememberMe);
Run Code Online (Sandbox Code Playgroud)
基于Sharplab.io反编译,应该为生成的属性发出属性。
如果没有此目标,属性将作为相应记录构造函数参数上的属性发出。
| 归档时间: |
|
| 查看次数: |
1371 次 |
| 最近记录: |