You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core 7中避免可空引用类型警告

关于ASP.NET Core 7中频繁出现CS8602可空引用类型警告的问题

我之前使用ASP.NET Core 5开发项目时很少遇到空警告,但近期启动ASP.NET Core 7新项目后,频繁遭遇CS8602等可空引用类型警告,不得不添加大量空检查语句,导致代码量显著增加。以下是联系表单及reCAPTCHA验证的控制器与模型代码示例,若移除空检查则会出现可能为空的警告,请问我在.NET新版本中哪里操作有误?

namespace Chesapeake_Tees_API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ContactUsController : ControllerBase
{

private readonly ILogger<ContactUsController> _logger;
private readonly IEmailService _emailService;
private readonly string? reCaptchaKey = "";

public ContactUsController(IConfiguration configuration, ILogger<ContactUsController> logger, IEmailService emailService)
{
    _logger = logger;
    _emailService = emailService;
    reCaptchaKey = configuration["CFTunrstileSecretKey"];
}

[HttpPost(Name = "PostContactUs")]
[EnableRateLimiting("api")]
public async Task<IActionResult> Post([FromBody] CustomerInquiry customerInquiry)
{
    try
    {
        if (reCaptchaKey != null && customerInquiry.Token != null)
        {
            var dictionary = new Dictionary<string, string>
                {
                    { "secret", reCaptchaKey },
                    { "response", customerInquiry.Token }
                };

            var postContent = new FormUrlEncodedContent(dictionary);

            HttpResponseMessage? recaptchaResponseHTTP = null;
            string? reCaptchaResponseJSON;

            // Call recaptcha api and validate the token
            using (var http = new HttpClient())
            {
                recaptchaResponseHTTP = await http.PostAsync("https://challenges.cloudflare.com/turnstile/v0/siteverify", postContent);
                reCaptchaResponseJSON = await recaptchaResponseHTTP.Content.ReadAsStringAsync();
            }

            var reCaptchaResponse = JsonSerializer.Deserialize<ReCaptchaResponse>(reCaptchaResponseJSON);

            if (recaptchaResponseHTTP.IsSuccessStatusCode)
            {
                if (reCaptchaResponse == null)
                {
                    return Ok($"Message: Error code 503, unable to verify reCaptcha token");
                }
                else
                {
                    if (reCaptchaResponse.Success)
                    {
                        EmailMessage emailMessage = new EmailMessage();

                        emailMessage.From = new Contact { DisplayName = "Chesapeake Tees", EmailAddress = "site@chesapeaketees.com" };
                        emailMessage.To.Add(new Contact { DisplayName = "Chesapeake Tees", EmailAddress = "info@chesapeaketees.com" });
                        emailMessage.ReplyTo = new Contact { DisplayName = customerInquiry.FirstName + " " + customerInquiry.LastName, EmailAddress = customerInquiry.EmailAddress };
                        emailMessage.Subject = "Custome Inquiry";
                        emailMessage.Body = customerInquiry.Message;
                        await _emailService.SendEmailAsync(emailMessage);
                        return Ok("Message: Success - email sent");
                    }
                    else
                    {
                        string? errors = null;

                        if (reCaptchaResponse.ErrorCodes != null)
                        {
                            errors = string.Join(",", reCaptchaResponse.ErrorCodes);
                        }
                        return Ok($"Message: Error code 500, {errors}");

                    }
                }
            }
            else
            {
                return Ok($"Message: Error code 503, unable to verify reCaptcha token");
            }
        }
        else
        {
            return Ok($"Message: Error code 503, unable to verify reCaptcha token");
        }
    }
    catch (Exception ex)
    {
        _logger.LogInformation("Message: Error: " + ex.ToString(), DateTime.UtcNow.ToLongTimeString());
        throw;
    }
}
}

我使用的模型已标记可空类型(设置默认值似乎无法解决父类的警告,仅可能解决单个属性的警告),代码如下:

public class ReCaptchaResponse
{
    [JsonPropertyName("success")]
    public bool Success { get; set; }

    [JsonPropertyName("cdata")]
    public string? CData { get; set; }

    [JsonPropertyName("challenge_ts")]
    public DateTime ChallengeTs { get; set; } // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)

    [JsonPropertyName("hostname")]
    public string? HostName { get; set; }    // the hostname of the site where the reCAPTCHA was solved

    [JsonPropertyName("error-codes")]
    public string[]? ErrorCodes { get; set; }
}

public class CustomerInquiry
{
    [Required]
    public string FirstName { get; set; } = "";

    [Required]
    public string LastName { get; set; } = "";

    [Required]
    [Phone]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$")]
    public string PhoneNumber { get; set; } = "";

    [Required]
    [EmailAddress]
    public string EmailAddress { get; set; } = "";

    [Required]
    public string Message { get; set; } = "";

    [Required]
    public string Token { get; set; } = "";
}

内容的提问来源于stack exchange,提问作者Qiuzman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:55:15