yes*_*man 12 c# c#-8.0 asp.net-core-6.0
我在 .Net 6 中创建了一个非常简单的 ASP.Net WebAPI 项目。给定以下控制器方法:
[HttpPost]
public async Task DoStuff(MyClass input)
{
// snip
}
Run Code Online (Sandbox Code Playgroud)
看起来MyClass像这样:
public class MyClass
{
public string MyData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
将其发布到DoStuffASP.Net 早期版本中允许使用的方法:
{
MyData: null
}
Run Code Online (Sandbox Code Playgroud)
string?然而现在,除非我将 MyData 声明为a 而不是 ,否则它会给出 400 响应string。我的问题是该类MyClass无法更改,因此我无法更新MyData为 type string?。有没有办法禁用 ASP.Net 对 MyClass 属性执行的自动 null 验证?添加<Nullable>disable</Nullable>到WebAPI项目的csproj文件似乎没有做任何事情。我当前的 csproj 如下所示:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Platforms>x64</Platforms>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<NoWarn>1701;1702;1591</NoWarn>
<UserSecretsId>MyProject</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AnotherProject.csproj" />
</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
Dav*_*idG 23
这是 C# 8可空引用类型的一项功能,在 .NET 6 中它们默认启用。要关闭它,请在您的 csproj 文件中添加此行<Nullable>disable</Nullable>。例如:
<PropertyGroup>
<Nullable>disable</Nullable>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
另外,如果 MyClass 在另一个项目中,<Nullable>disable</Nullable>也添加到那里。
如果您在csproj中禁用 nullable ,则在使用可为 null 运算符 ( ? ) 时可能会导致警告。将以下代码添加到您的 .editorconfig 将允许您使用这两种方法(可为空或不可为空),而不会出现任何其他警告。
您可以在解决方案项目中编辑.editorconfig文件。在[*.{cs,vb}]部分的末尾添加了这些行
#### Naming styles ####
[*.{cs,vb}]
# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
dotnet_diagnostic.CS8618.severity = none
# CS8601: Possible null reference assignment.
dotnet_diagnostic.CS8601.severity = none
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11989 次 |
| 最近记录: |