如何在asp.net核心中验证json请求正文为有效的json [英] How to validate json request body as valid json in asp.net core

查看:43
本文介绍了如何在asp.net核心中验证json请求正文为有效的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 asp.net core 2.1 中,当控制器动作设置为:

 [HttpPost]公共 JsonResult GetAnswer(SampleModel 问题){返回 Json(question.Answer);}

其中 SampleModel 定义为:

公共类 SampleModel{[必需的]公共字符串问题{得到;放;}公共字符串答案 { 得到;放;}}

这仍被视为有效请求:

<代码>{"问题": "一些问题","问题": "一些问题 2",答案":一些答案"}

在控制器中,我可以看到第二个问题是模型的值,模型是否有效.

问题是如何在模型绑定之前仅将请求正文验证为有效的 JSON?

解决方案

根据

In asp.net core 2.1, when a controller action is set as:

    [HttpPost]
    public JsonResult GetAnswer(SampleModel question)
    {               
        return Json(question.Answer);
    }

where the SampleModel is defined as:

public class SampleModel
{
    [Required]
    public string Question { get; set; }

    public string Answer { get; set; }
}

this is still considered as valid request:

{
  "question": "some question",
  "question": "some question 2",
  "answer": "some answer"
}

In the controller I can see that second question is the value of model and model is valid.

Question is how to validate just body of request as valid JSON even before model binding?

解决方案

According to Timothy Shields's answer, it's hard to say that would be an invalid json if we have duplicated property keys.

And when using ASP.NET Core 2.1, it won't throw at all.

As of 12.0.1, the Newtonsoft.Json has a DuplicatePropertyNameHandling settings. It will throw if we set DuplicatePropertyNameHandling.Error and pass a duplicated property. So the easiest way I can come up is to create a custom model binder. We could deserialize the JSON and change the ModelState if it throws .

Fristly, install the latest Newtonsoft.Json:

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
  </ItemGroup>

and then register a JsonLoadSettings option as a singleton service for later reuse :

services.AddSingleton<JsonLoadSettings>(sp =>{
    return new JsonLoadSettings { 
        DuplicatePropertyNameHandling =  DuplicatePropertyNameHandling.Error,
    };
});

Now we can create a custom model binder to deal with duplicated properties :

public class XJsonModelBinder: IModelBinder
{
    private JsonLoadSettings _loadSettings;
    public XJsonModelBinder(JsonLoadSettings loadSettings)
    {
        this._loadSettings = loadSettings;
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); }
        var modelName = bindingContext.BinderModelName?? "XJson";
        var modelType = bindingContext.ModelType;

        // create a JsonTextReader
        var req = bindingContext.HttpContext.Request;
        var raw= req.Body;
        if(raw == null){ 
            bindingContext.ModelState.AddModelError(modelName,"invalid request body stream");
            return Task.CompletedTask;
        }
        JsonTextReader reader = new JsonTextReader(new StreamReader(raw));

        // binding 
        try{
            var json= (JObject) JToken.Load(reader,this._loadSettings);
            var o  = json.ToObject(modelType);
            bindingContext.Result = ModelBindingResult.Success(o);
        }catch(Exception e){
            bindingContext.ModelState.AddModelError(modelName,e.ToString()); // you might want to custom the error info
            bindingContext.Result = ModelBindingResult.Failed();
        }
        return Task.CompletedTask;
    }
}

To enable read the Request.Body multiple times, we could also create a dummy Filter:

public class EnableRewindResourceFilterAttribute : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.HttpContext.Request.EnableRewind();
    }
    public void OnResourceExecuted(ResourceExecutedContext context) { }
}

Lastly, decorate the action method with [ModelBinder(typeof(XJsonModelBinder))] and EnableRewindResourceFilter:

    [HttpPost]
    [EnableRewindResourceFilter]
    public JsonResult GetAnswer([ModelBinder(typeof(XJsonModelBinder))]SampleModel question)
    {               
        if(ModelState.IsValid){
            return Json(question.Answer);
        }
        else{
            // ... deal with invalid state
        }
    }

Demo :

这篇关于如何在asp.net核心中验证json请求正文为有效的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆