psur
psur

Reputation: 4519

How to override default deserialization for Controller Action in ASP.NET Core?

I have an Action in Controller which has an argument of type Class1

[HttpPost]
public IActionResult Create(Class1 c)
{
}

I send data to it using JQuery's Ajax function.

I would like to write my own code to deserialize SampleProperty:

class Class1
{
    public string SampleProperty { get; set; }
}

Is it possible? I would like to override default deserialization.

I've tried many things, for example writing converter:

public class SamplePropertyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
                                    object existingValue, JsonSerializer serializer)
    {
        if ((string)existingValue == "abc")
            return "abc123";
        else
            return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value,
                                   JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanWrite => false;
    public override bool CanRead => true;
}

and then using it like this:

class Class1
{
    [JsonConverter(typeof(SamplePropertyConverter))]
    public string SampleProperty { get; set; }
}

but in such case SamplePropertyConverter is not used at all. I also tried to add it in Startup, but then I see that it enters CanConvert method, but only for some other requests, not sending Class1 to Create Action.

Upvotes: 1

Views: 2288

Answers (1)

Ryan
Ryan

Reputation: 20126

If you do not use json, you could use custom model binding to make it.

1.Assume you have ajax code:

 var data = { "SampleProperty": "abc"};
   $(document).ready(function () {
        $.ajax({
            url: '/Test/Create',
            type: 'POST',
            data: data,
            success: function () {

            }

        });
   });

2.Controller:

[HttpPost]
public IActionResult Create(Class1 c)
{
}

3.Class1.cs:

class Class1
{
    [ModelBinder(BinderType = typeof(TestModelBinder))]
    public string SampleProperty { get; set; }
}

4.TestModelBinder.cs

public class TestModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));
        var values = bindingContext.ValueProvider.GetValue("SampleProperty");

        string result = "";

        if (values.FirstValue == "abc")
        {
            result = "abc123";
        }else
        {
            result = values.FirstValue;
        }
        bindingContext.Result = ModelBindingResult.Success(result);
        return Task.CompletedTask;
    }
}

Upvotes: 2

Related Questions