Home > front end >  Is it possile to return .NET object from controller to middleware
Is it possile to return .NET object from controller to middleware

Time:12-05

I was working on one of the requirements, where I need to modify result data in middleware (not any MVC Filters due to some other services injected through middleware).

In middleware I was getting data in json format and then deserializing that data then updating that data and finally serializing to JSON and sending it back as a response.

I don't want to serialize data in MVC pipeline so I tried to remove output formator but that didn't work for me and throwing error.

services.AddControllers(options =>
        {
            options.OutputFormatters.Clear();
        });

Is there any solution to get the .Net object in the pipeline and modify that object (as we do in MVC filter) and then serialize at last?

CodePudding user response:

I am not sure whether it fits your requirements but you can use HttpContext to store some data in the scope of the request. There is a 'Items' key-value collection.

CodePudding user response:

Beside the other suggestion to use Items of HttpContext, I want to note that you can inject services into Action Filters:

public class ResultFilter : IActionFilter
{

    // Inject anything you want
    IHostEnvironment env;
    public ResultFilter(IHostEnvironment env)
    {
        this.env = env;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is OkObjectResult result)
        {
            result.Value = JsonSerializer.Serialize(new
            {
                Value = result.Value,
                Environment = this.env.EnvironmentName,
            });
        }
    }

    public void OnActionExecuting(ActionExecutingContext context) { }
}

Register to DI Builder:

services.AddScoped<ResultFilter>();

Apply to action/controller:

    [HttpGet, Route("/test"), ServiceFilter(typeof(ResultFilter))]
    public IActionResult ReturnOk()
    {
        return this.Ok(new
        {
            Value = 1,
        });
    }

Testing by accessing the URL:

{"Value":{"Value":1},"Environment":"Development"}
  • Related