繁体   English   中英

我如何获取我的Json的参数并在发布Post Int Web API 2 .net之前进行验证?

[英]How i can get the arguments of my Json and validate before of make a post int web api 2 .net?

例如,下一个json,我要在发布信息之前验证金额

{
    "amount":"10"
}

我可以创建一个过滤器类并获取此参数并对其进行验证,我必须进行强制转换吗?

public class ValidateModelTransaction : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var posted = actionContext.Request.Content.ReadAsStringAsync().Result;
        TransactionModel amount = JsonConvert.DeserializeObject<TransactionModel>(posted);
    }
}

您可以创建一个自定义函数,该函数使用JsonTextReader来读取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;
}

使用委托作为参数( Func<int, bool> validateFunc )可以让您在不同的情况下重用该方法-例如:

string json = @"{""amount"":""10""}";

bool isPositiveAmount = ValidateAmount(json, x => x > 0); // returns true
bool isBetween100And200 = ValidateAmount(json, x => x > 100 && x < 200); // returns false

编辑

ValidateAmount方法最终可以在ActionFilterAttribute

示例-检查金额是否为正:

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)
        {
            // ....
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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