我正在尝试在Azure API Manager中的API上设置一个入站策略,该策略在将其传递给后端之前在Post Request Body中验证JSON。
我应该使用JSON架构并对(如何?)进行验证,或者如果我应该编写自己的代码,请使用context.request.body检查请求正文中的每个字段,或者尝试尝试尝试一下验证APIM中的请求主体,应该留给后端吗?
我们当前正在使用<set-body>
的API操作策略验证(并在需要时重新形状)。在此政策中,我们正在收集所有错误,然后我们将这些错误与例外:
<set-body>@{
var body = context.Request.Body.As<JObject>(true);
string businessSystemID = context.Request.Headers.GetValueOrDefault("SenderBusinessSystemID", "");
var result = new JObject();
string cleanUp = body.ToString().Replace("rn","");
var root = JObject.Parse(cleanUp);
var valid = false;
var errors = new JArray();
var returnValue = new JObject();
returnValue["errors"] = errors;
if(root["CostAllocation"] != null)
{
if(businessSystemID != string.Empty)
{
root["CostAllocation"]["SenderBusinessSystemID"] = businessSystemID;
}
if(root["CostAllocation"]["ReferenceID"] != null)
{
var referenceIDValidator = @"^[A-Z0-9]{0,35}$";
var referenceID = root["CostAllocation"]["ReferenceID"];
valid = new Regex(referenceIDValidator, RegexOptions.IgnoreCase).Match(referenceID.ToString()).Success;
if(!valid)
{
var error = new JObject();
error["property"] = "ReferenceID";
error["validator"] = referenceIDValidator;
error["value"] = referenceID;
error["message"] = "No valid 'ReferencedId'";
errors.Add(error);
}
}
if(root["CostAllocation"]["UserID"] != null)
{
var userIDValidator = @"^[w]{4,12}$";
var userID = root["CostAllocation"]["UserID"];
valid = new Regex(userIDValidator, RegexOptions.IgnoreCase).Match(userID.ToString()).Success;
if(!valid)
{
var error = new JObject();
error["property"] = "UserID";
error["validator"] = userIDValidator;
error["value"] = userID;
error["message"] = "No valid 'UserID'";
errors.Add(error);
}
}
...
if(errors.Count > 0)
{
throw new Exception(returnValue.ToString());
}
return root.ToString(Newtonsoft.Json.Formatting.None);
}</set-body>
例外被<on-error>
捕获,处理和格式化:
<on-error>
<choose>
<when condition="@(context.LastError.Message.Contains("Expression evaluation failed")==true)">
<set-status code="400" reason="Bad request" />
</when>
<otherwise>
<set-status code="500" reason="Error" />
</otherwise>
</choose>
<set-body template="none">@{
return context.LastError.Message.Replace("Expression evaluation failed.","").Trim();
}</set-body>
<base />
</on-error>
我们知道,这种方法的编码工作很高,更愿意对直接在API管理中直接支持的JSON模式检查。在后端进行架构检查处理,并通过传递请求而增加延迟是我们的选择。
我当前想的一个选项是在API CI/CD流程中解析JSON模式,生成通用验证&amp;在API操作策略中替换它。
验证有效载荷是完全可以的。请注意,这样做将需要在APIM侧缓存整个请求主体,而默认情况下并未完成。JSON Schema验证器在策略表达式中不可用,因此您必须求助于手动验证。