Search code examples
c#.netserializationasp.net-web-api2

FluentResults throws InvalidOperationException on getting or serializing Value


Note : Please someone with a higher reputation tag FluentResults here .

I am using .Net 6 and have problem with FluentResults 3.5.0. Suppose I have the following class :

 public class Person
    {
        public FluentResults.Result<List<Person>> GetAll()
        {
            return FluentResults.Result.Fail("SomeError1");
        }
    }

And the following API Methods :

    [HttpGet("Normal")]
    public async Task<ActionResult<object>>? Normal()
    {

        var r1 = FluentResults.Result.Fail("SomeError2");
        return BadRequest(r1);
    }

    [HttpGet("Buggy")]
    public async Task<ActionResult<object>>? Buggy()
    {
        Person p = new();
        return BadRequest(p.GetAll());
    }

the first one is work fine as expected. With a 400 error code and the following result :

enter image description here

But the second one which I want to use returns internal server error(500):

enter image description here

and I think the problem is with the Result.Value throwing InvalidOperationException so it can not be serialized. How can I fix this code ?


Solution

  • I'am the maintainer of FluentResults.

    It is not recommended to serialize result objects from FluentResults. Why? See https://github.com/altmann/FluentResults#serializing-result-objects-aspnet-webapi-hangfire

    Your first scenario is working fine because you return a Result object. A Result object has no Value property. In your second scenario you return a Result object with a Value property. If you return a failed Result object and you call result.Value then you get the exception which you see. If you really want to use Result objects from FluentResults in your public api then maybe you can setup your serialization library to ignore the Value property. The property ValueOrDefault is safe to call because it will return the default value if the result is in failed state. https://github.com/altmann/FluentResults#processing-a-result Please read the readme for more information.