Search code examples
c#asp.net-mvcresthttp-postasp.net-core-2.0

.net core rest api post end - read query string from body


In .net core 2.1,

On HTTP post endpoint,

Is it possible to read query string parameter from body?

sample request body:

name="zakie"&country="uswest"&state="california"


Solution

  • You could custom TextInputFormatter like below:

    public class CustomInputFormatter : TextInputFormatter
    {
        public CustomInputFormatter()
        {
            SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/plain"));
            SupportedEncodings.Add(Encoding.UTF8);
            SupportedEncodings.Add(Encoding.Unicode);
        }
        protected override bool CanReadType(Type type)
        {
            return type == typeof(TestModel);
        }
        public override async Task<InputFormatterResult> ReadRequestBodyAsync(
            InputFormatterContext context, Encoding effectiveEncoding)
        {
            var reader = new StreamReader(context.HttpContext.Request.Body, effectiveEncoding);
            var line = await reader.ReadToEndAsync();
            var split = line.Split("&".ToCharArray());
            var model = new TestModel();
            foreach (var item in split)
            {
                var list = item.Split("=");
                var value = list[1].Replace("\"", "");
                model.GetType()
                    .GetProperty(list[0], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
                    .SetValue(model, value, null);
            }
            return await InputFormatterResult.SuccessAsync(model);
        }     
    }
    

    Test Model:

    public class TestModel
    {
        public string Name { get; set; }
        public string Country { get; set; }
        public string State { get; set; }
    }
    

    Controller:

    public void Test([FromBody]TestModel model)
    {
        //do your stuff..
    }
    

    Register the service:

    services.AddMvc(options=> {
        options.InputFormatters.Insert(0, new CustomInputFormatter());
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    

    Result:

    enter image description here