CustomValidation属性 - NullReferenceException

时间:2018-03-02 13:22:44

标签: c# .net-core-2.0

我为我在MVC应用程序中使用的模型编写了一个CustomValidation属性。

它并不复杂,但由于某种原因,我得到一个非常奇怪的NullReferenceException错误。我已经把这个权利剥离到了绝对的最低限度,只是为了试图超越它。

代码在这里绊倒if (value != null)

如果我在它上面的行上放置一个断点,那么踩到断点就会产生异常。

奇怪的是,我可以将value放入一个字符串变量中,我可以看到它是有效的并且存在。

然后我尝试更改if语句以检查该变量是否为null而不是value,并且ALSO产生错误。

我做错了什么?

从控制器返回的实际错误响应如下。它引用的行是If语句。

<h1>An unhandled exception occurred while processing the request.</h1>
        <div class="titleerror">NullReferenceException: Object reference not set to an instance of an object.</div>
        <p class="location">TechsportiseOnline.Helpers.CustomValidations&#x2B;BibValidatorAttribute.IsValid(object value, ValidationContext validationContext) in 
            <code title="C:\Users\matthew.warr\Documents\Git\Website\TechsportiseOnline\Helpers\CustomValidations.cs">CustomValidations.cs</code>, line 22
        </p>

CustomAttribute类

public class BibValidatorAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        value = (string)value;

        if (value != null)
        {
            RaceEntry raceEntry = (RaceEntry)validationContext.ObjectInstance;

            var _context = (ApplicationDbContext)validationContext.GetService(typeof(ApplicationDbContext));

            var databaseBib = _context.RaceEntries.FirstOrDefault(c => c.Id == raceEntry.Id).BibNumber.ToString();

            if (value == databaseBib)
                {
                    return new ValidationResult("The bib number entered already exists");
                }
                else
                {
                    return ValidationResult.Success;
                }
        }
        else
        {
            return ValidationResult.Success;
        }              
    }
}

模型

public partial class RaceEntry
    {

        public long Id { get; set; }
        public long RaceID { get; set; }
        [NotMapped]
        public string RaceName { get; set; }
        [NotMapped]
        [DisplayFormat(DataFormatString = "{0:dd MMMM yyyy}")]
        public DateTime RaceDate { get; set; }
        [IgnoreDataMember]
        public string OwnerID { get; set; }
        [IgnoreDataMember]
        public string AthleteUserId { get; set; }
        [Display(Name = "Title")]

        public string Title { get; set; }
        [Display(Name = "First Name *")]
        [Required]
        public string FirstName { get; set; }
        [Display(Name = "Last Name *")]
        [Required]
        public string LastName { get; set; }
        [Display(Name = "Email Address")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        [RequiredOnlineOnly]
        public string Email { get; set; }
        [Display(Name = "Date Of Birth *")]
        [DataType(DataType.Date)]
        [DateOfBirth]
        [DisplayFormat(DataFormatString = "{0:dd MMMM yyyy}")]
        public DateTime DateOfBirth { get; set; }
        [Display(Name = "Gender *")]
        public string Gender { get; set; }
        [Display(Name = "EA Affiliation Number")]
        public string EANumber { get; set; }
        [Display(Name = "Club Name")]
        public string Club { get; set; }
        [Display(Name = "Team")]
        public string Team { get; set; }
        [Display(Name = "Bib/Race Number")]
        [BibValidator (ErrorMessage = "The bib number you have entered already exists")]
        public string BibNumber { get; set; }
        public DateTime EntryDateTime { get; set; }
        [IgnoreDataMember]
        public DateTime LastUpdated { get; set; }
        public string Status { get; set; }
        [Display(Name = "Mobile Phone")]
        public string MobilePhone { get; set; }
        [IgnoreDataMember]
        public string FullMobilePhone { get; set; }
        [IgnoreDataMember]
        [Display(Name = "Number")]       
        public string HouseNumber { get; set; }
        [Display(Name = "Address *")]
        [RequiredOnlineOnly]
        public string Address1 { get; set; }
        [Display(Name = "Address 2")]
        public string Address2 { get; set; }
        [Display(Name = "Town/City")]
        public string City { get; set; }
        [Display(Name = "State")]
        public string State { get; set; }
        [Display(Name = "County")]
        public string County { get; set; }
        [Display(Name = "Country")]
        public string Country { get; set; }
        [Display(Name = "Postcode *")]
        [RequiredOnlineOnly]
        public string PostCode { get; set; }
        public string Source { get; set; }
        [Display(Name = "Entry Type")]
        public string EntryType { get; set; }

        public bool Premium { get; set; }
        public bool SMSSent { get; set; }
        public bool FinalInstructionsSent { get; set; }
        public bool ResultEmailSent { get; set; }
        public bool Refunded { get; set; }
        public string StripeCode { get; set; }
        public decimal AmountPaid { get; set; }
        public string AmountPaidCurrency { get; set; }

        [IgnoreDataMember]
        public string BillingName { get; set; }
        [IgnoreDataMember]
        public string BillingAddress1 { get; set; }
        [IgnoreDataMember]
        public string BillingAddress2 { get; set; }
        [IgnoreDataMember]
        public string BillingCity { get; set; }
        [IgnoreDataMember]
        public string BillingState { get; set; }
        [IgnoreDataMember]
        public string BillingCounty { get; set; }
        [IgnoreDataMember]
        public string BillingCountry { get; set; }
        [IgnoreDataMember]
        public string BillingPostCode { get; set; }
        [IgnoreDataMember]
        public string BillingEmail { get; set; }

    }

控制器的相关部分

[HttpPost]
        public IActionResult Create([FromBody] RaceEntry item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            //Check bib number
            if (!ModelState.IsValid)
            {
                return BadRequest("Bib number already exists");
            }

0 个答案:

没有答案