Home > Blockchain >  Can BindProperty extract data from posted JSON?
Can BindProperty extract data from posted JSON?

Time:11-22

ASP.NET Core has this BindProperty attribute that you can use to bind controller-level properties to parameters of HTTP request.

[BindProperty (SupportsGet=true)]
public string Name { get; set; }

However, it does not bind to the request, if it's Content-Type: application.json and the body is:

{
    "name": "Somebody"
}

Can we configure it to bind to JSON too?

CodePudding user response:

Request body needs to bind a complex model, So you can't bind string directly, If you want to bind this value, Here are two methods.

The first method is to create a class include this property:

public class Test
    {
        public string Name { get; set; }
    }

Then bind this class in your code:

    [BindProperty]
    [FromBody]
    public Test test { get; set; }

The second method is custom model binding:

public class MyBinder : IModelBinder
    {
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
                throw new ArgumentNullException(nameof(bindingContext));

            var modelName = bindingContext.FieldName;

            string bodyAsText = await new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync();
            if (bodyAsText == null)
            {
                return;
            }
            
            //check if the key equals fieldName
            var key = bodyAsText.Trim().Substring(12, modelName.Length);
            if (!modelName.Equals(key))
            {
                return;
            }

            //get the value.
            var result = bodyAsText.Split(":")[1];
            var a = result.Substring(2, result.IndexOf("\r") - 3);

            bindingContext.Result = ModelBindingResult.Success(a);
        }
    }

Then you can bind a string value:

[BindProperty]
[ModelBinder(BinderType = typeof(MyBinder))]
public string Name { get; set; }
  • Related