In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
What this article shares to you is about how to analyze the interface input verification of WebApiClient. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
1. Purpose of the article
With the continuous improvement of WebApiClient, more and more developers choose WebApiClient to replace the native HttpClient. The new features of WebApiClient's API parameter input validity verification are described below.
2.DataAnnotations introduction
In asp.net mvc server programming, when we create a model, we can use the verification features related to System.ComponentModel.DataAnnotations, together with the mvc framework, to do the effect of front-end and back-end two-way input verification.
Public class UserInfo {[Required] [StringLength (10, MinimumLength = 1)]
Public string Account {get; set;} [Required] [StringLength (10, MinimumLength = 6)]
Public string Password {get; set;}}
The above Required is the verification feature. When the asp.net mvc is bound to the model, it will verify it again, and the verification result will be put in the controller's ModelState property. Of course, System.ComponentModel.DataAnnotations is not specific to asp.net mvc, but comes with the underlying library, which means it can be used in any framework.
3. Input verification of interface parameter values
The Validator static class mentions ValidateObject-related methods to verify the instance and the attribute values of the instance. WebApiClient uses the Validator class to complete the parameter value input verification of the interface method:
/ / /
/ / provide validation of input validity of parameter values and attribute values of parameters
/ / /
Static class ParameterValidator
{
/ / /
/ / whether the properties of the type need to verify the cache
/ / /
Private static readonly ConcurrentCache cache = new ConcurrentCache ()
/ / /
/ / returns whether property verification is required
/ / /
/ instance
/ / /
Private static bool IsNeedValidateProperty (object instance)
{
If (instance = = null)
{
Return false
}
Var type = instance.GetType ()
If (type = = typeof (string) | | type.GetTypeInfo (). IsValueType = = true)
{
Return false
}
Return cache.GetOrAdd (type, t = > t.GetProperties () .Any (p = > p.CanRead & & p.IsDefined (typeof (ValidationAttribute), true)
}
/ / /
/ / verify the validity of the input of parameter values
/ / verify the validity of the input of the attribute value of the parameter
/ / /
/ / Parameter description
/ / whether to verify the attribute value
/ / /
Public static void Validate (ApiParameterDescriptor parameter, bool validateProperty)
{
Var name = parameter.Name
Var instance = parameter.Value
Foreach (var validation in parameter.ValidationAttributes)
{
Validation.Validate (instance, name)
}
If (validateProperty = = true & & IsNeedValidateProperty (instance) = = true)
{
Var ctx = new ValidationContext (instance) {MemberName = name}
Validator.ValidateObject (instance, ctx, true)
}
}
}
4. The DataAnnotations statement of interface parameters 4.1 declares verification of parameter values
For example, the GetByIdAsync method has a parameter of id, and the server requires a string with a maximum length of 10. We can modify the parameter id with Required and StringLength (10). When the API is called, WebApiClient validates the id value, and throws an exception of ValidationException if it fails.
/ / GET webapi/user/GetById?id=id001// Return HttpResponseMessage [HttpGet ("webapi/user/GetById/ {id}")] [BasicAuth ("userName", "password")] ITask GetByIdAsync ([Required, StringLength (10)] string id)
For custom model types, the input validation of the attribute is performed automatically as long as the relevant DataAnnotations,WebApiClient is declared in the attribute.
Public class UserInfo
{
[Required]
[StringLength (10, MinimumLength = 1)]
Public string Account {get; set;}
[Required]
[StringLength (10, MinimumLength = 6)]
Public string Password {get; set;}
}
/ / POST webapi/user/UpdateWithJson
/ / Body {"Account": "laojiu", "Password": "123456"}
/ / Return json or xml content
[HttpPost ("webapi/user/UpdateWithJson")]
ITask UpdateWithJsonAsync (
[JsonContent ("yyyy-MM-dd HH:mm:ss")] UserInfo user)
When the user parameter is not null, its Account and Password properties are validated.
4.3 declare the parameter value and verify the attribute value of the parameter at the same time
For example 4.2, if we want the value of the user parameter not to be null, we can declare the method as follows:
/ / POST webapi/user/UpdateWithJson// Body {"Account": "laojiu", "Password": "123456"} / / Return json or xml content [HttpPost ("webapi/user/UpdateWithJson")] ITask UpdateWithJsonAsync ([Required] [JsonContent ("yyyy-MM-dd HH:mm:ss")] UserInfo user); 5. Disable property validation for parameters
If the properties of your model have been declared for verification, but you do not want WebApiClient to perform property value verification, you can disable property verification in the configuration item when creating an interface instance:
Var config = new HttpApiConfig {UseParameterPropertyValidate = false}; var client = HttpApiClient.Create (config); this is how to analyze the interface input verification of WebApiClient. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.