Home > database >  Return specific type from IAsyncActionFilter
Return specific type from IAsyncActionFilter

Time:01-21

I have a bunch of functions that are meant to have similar logic that i could wrap using attributes in c#, but the wrapper i'm currently trying to create should return a response value that is a custom type that simply represents a respond from server

Response class:

public class Response
{
    public int StatusCode { get; set; }
    public string Message { get; set; }
}

Method i want to wrap to (simple logic for demonstration purposes):

void SentRequest()
{
    Request(parameter: "simple text");
}

And lets say i want to wrap this method with attribute class, which can create a response value:

class StorageServiceFilter : IAsyncActionFilter
{
    private Response _response;

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        await next();

        _response.StatusCode = 200;
        _response.Message = "Upload successful";
    }
}

Now, is it possible to return my _response? I already know about ActionExecutingContext.Result property, but unfortunately it returns only IActionResult type, which is not suitable for my case.

PS:

Forgot to mention that IAsyncActionFilter has only the implementation for Task OnActionExecutionAsync that makes impossible to use Task<T> as a return type

CodePudding user response:

You can get the context returned by await next() and set the Result property. Something like this:

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    var resultContext = await next();
    resultContext.Result = new ObjectResult(
        new Response() { StatusCode = 200, Message = "Upload successful" });
}

Please note that it will cause bypassing the remaining action filters:

From ASP.NET Core In Action book:

Setting the Result property on context short-circuits the pipeline. But, due to the position of the action filter stage, only the action method execution and later action filters are bypassed; all the other stages of the pipeline run as though the action had executed as normal.

  •  Tags:  
  • c#
  • Related