简体   繁体   中英

Having issues in doing a Custom Validation for a GUID property in API asp.NET core C#

This is the class in which I'm trying to validate the serialnumber property(you can find it in the code below named as NumerodiSerie ). I'm testing it with CRUD operations, in particular a POST.

The main problem is if I start the program and try to stop it in my validation function it simply won't enter in it cause swagger gives me an error before which is the following:

the JSON value cannot be converted in system.guid .

It only enters my validate function when I have a valid Guid(I think that I have this error because I was trying to test it(by deleting one number from the guid and so on) in order to see if my validation function worked).

public class Smartphone
{
    public string Produttore { get; set; }

    public string Modello { get; set; }

    [Range(1,100, ErrorMessage ="la ram non è compresa tra 1 e 100")]
    public int DimensioniRam { get; set; }

    [CustomValidation(typeof(Validator),"Validazionearchiviazione")]
    public int Memoria { get; set; }

    [Range(0,2, ErrorMessage ="la cpu non è compresa tra 0 e 2")]
    public ProduttoreProcessore CpuMaker { get; set; }

    [CustomValidation(typeof(Validator),"ValidateGuid")]
    public Guid NumerodiSerie { get; set; }
}

POST

    [HttpPost]
    public HttpResponseMessage CreateSmartphone(Smartphone s)
    {                                                                    
        Guid g = Guid.NewGuid();//auto generating GUID
        s.NumerodiSerie = g;//serialnumber property
        if (_cantinetta.Any(x => x.NumerodiSerie == s.NumerodiSerie))
        {
            return new 
            HttpResponseMessage(System.Net.HttpStatusCode.NotAcceptable);
            throw new Exception("/error");//errorcontroller
        }
        else
        {
            _cantinetta.Add(s);//_cantinetta is the list in which I store data
            Serializzajson();//serialize the json and writes it in a file
            return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
    }

      
       

CUSTOM VALIDATION METHOD

 public static ValidationResult ValidateGuid(Guid value, ValidationContext validationContext)
    {
        
        if (value.ToString().Length < 36 || validationContext.ObjectType != typeof(Guid) || 
         validationContext.ObjectType == typeof(Guid) && 
         validationContext.ObjectType.ToString().Length < 36)
        {
            return new ValidationResult("not a valid GUID");
        }
        return ValidationResult.Success;

    }

I was tryng to do this in the method but it doesn't work as I would expected. any suggestion? the custom validation is a new topic for me and I'm studyng C# since 6 months so I'm a newbie. dunno why it is formatted like that in this question.I didn't write it like that and also this is my first question in this fantastic place. Have a Fantastic day. Edward.

Any reason you can't just do:

if (!Guid.TryParse(textValue, out var id) || id == Guid.Empty)
{
   // Not a GUID or empty
}
// id is now a guid.

As far as I know, there is no need to check the post value is Guid or not in the custom validation method, since the asp.net core model binder will check it automatically. Besides, if the model binder finds the value is not the right guid type, it will not go to the custom validation and directly add the modelstate error.

Like below:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM