简体   繁体   中英

Best way to handle HttpClient inside Model class in C#

I have a model. It has one property called country . I need to validate this property from a 3rd party service ie country is valid or not

I can think the following ways:

  1. Should I inject HttpClient inside the model constructor and call the 3rd party service inside the model itself?
  2. Should I create another service where I call the 3rd party service and inject the other service inside my model?
  3. Is there any better way to do this?

You can implement custom model validation like any other out of the box validators ([Required], [MaxLength], [Range], etc) available. I'm going to make the assumption that you're using some type of ASP.net MVC framework or Core (ApiController, Controller, etc). If you need custom validation of, say, MyModel.Country, you can have a custom validator attribute that decorate on the "Country" property of your model. You should avoid business logic code like validation within your model since models are usually for holding data.

To create a custom validator to validate the Country property. Reference to how to customize model validation. https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#custom-attributes

public ValidateCountryAttribute:ValidationAttribute{

   protected override ValidationResult IsValid(object value, ValidationContext 
                                              validationContext)
   {
         string countryPropertyValue = (string)value;
         //Validate your country
         if (!ValidCountry(countryPropertyValue){
              return new ValidationResult("Country is not valid");
         }         


        //Return Validation.Success
        return ValidationResult.Success;
    }
    private bool ValidCountry(string countryName){
      //code to validate against 3rd party goes here.

      return true;
    }
 }

On your Model class:

public class MyModel{

 [ValidateCountry]
 public string Country{get;set;}

}

When you receive MyModel in your controller's methods, you call ModelState.IsValid to determine if the MyModel instance you received is valid or not.

public class MyController:Controller{

    public void Post(MyModel model){

      if (!ModelState.IsValid){
       //MyModel has invalid country, do something....

      }
    }

}

The benefit of doing this approach is now the ValidateCountryAttribute can be put on any model class' property if you need Country validation. This approach allows for easier reuse and keeps validation business logic out of your model.

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