我有.Net Web API 2项目。它使用模型绑定进行操作。
[JsonSchemaValidationActionFilter("create-history-rfa-schema.json", typeof(CreateHistoryRfa.Command))]
public async Task<IHttpActionResult> CreateHistoryRfa(CreateHistoryRfa.Command command)
{
return Ok("The json is valid");
}
对于某些操作,我想借助json-schema验证请求。这是因为一些操作在不同的使用者之间共享,并且很容易向他们发送正文的json模式。而且,如果我正在使用json模式编写验证,则不想将其复制到DataAnnotations,我想使用json模式验证模型。
我的第一次尝试是实现ActionAttribute:
public override async void OnActionExecuting(HttpActionContext actionContext)
{
try
{
var stream = await actionContext.Request.Content.ReadAsStreamAsync();
stream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream);
string body = reader.ReadToEnd();
var jsonSchema = new JsonSchema(body, jsonSchemaName);
jsonSchema.ValidateJson();
}
catch(Exception exception)
{
actionContext.HandleJsonException(exception);
actionContext.HandleInternalException(exception);
}
}
您会注意到我必须搜索流,这是因为动作过滤器是在模型绑定器之后执行的,因此内容流已被读取到结束。
这种方法一直在起作用,但是突然其中一个动作的内容流将CanSeek设置为false,所以我无法将position设置为0 :(我不知道为什么搜索可能是错误的,我不知道我不知道如何处理该问题。我可以从操作方法中删除参数,但我想同时拥有:模型绑定程序和json验证。