For example, the next json, I want validate the amount before of make a post
{
"amount":"10"
}
Could I create a filter class and get this argument and validate it, I have to make a cast?
public class ValidateModelTransaction : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var posted = actionContext.Request.Content.ReadAsStringAsync().Result;
TransactionModel amount = JsonConvert.DeserializeObject<TransactionModel>(posted);
}
}
You can create a custom function that uses a JsonTextReader
to read the value of the amount
property, and takes a delegate as a parameter to validate the amount:
private static bool ValidateAmount(string json, Func<int, bool> validateFunc)
{
using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
{
reader.CloseInput = true;
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName && reader.Value.Equals("amount"))
{
int? amount = reader.ReadAsInt32();
if (!amount.HasValue)
{
return false;
}
bool isValid = validateFunc(amount.Value);
return isValid;
}
}
}
return false;
}
Using a delegate as a parameter ( Func<int, bool> validateFunc
) allows you to reuse the method in different scenarios - example:
string json = @"{""amount"":""10""}";
bool isPositiveAmount = ValidateAmount(json, x => x > 0); // returns true
bool isBetween100And200 = ValidateAmount(json, x => x > 100 && x < 200); // returns false
The ValidateAmount
method can eventually be used in an ActionFilterAttribute
.
Example - check if the amount is positive:
public class ValidateModelTransaction : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
bool isPositiveAmount = ValidateAmount(json, x => x > 0);
if (isPositiveAmount)
{
// ....
}
}
}
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.