Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DotNet Core Middleware Wrap Response

I have a simple controller action which looks like:

    public Task<IEnumerable<Data>> GetData()
    {
        IEnumerable<Data> data = new List<Data>();
        return data;
    }

I want to be able to inspect the return value from within the middleware so the JSON would look something like

{
  "data": [
  ],
  "apiVersion": "1.2",
  "otherInfoHere": "here"
}

So my payload always is within data. I know I can do this at a controller level but I don't wan to have to do it on every single action. I would rather do it in middleware once for all.

Here is an example of my middleware:

public class NormalResponseWrapper
{
    private readonly RequestDelegate next;

    public NormalResponseWrapper(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {                
        var obj = context;
        // DO something to get return value from obj
        // Create payload and set data to return value

        await context.Response.WriteAsync(/*RETURN NEW PAYLOAD HERE*/);
    }

Any ideas?

Got the value now but it's to late to return it

        try
        {
            using (var memStream = new MemoryStream())
            {
                context.Response.Body = memStream;
                await next(context);
                memStream.Position = 0;
                object responseBody = new StreamReader(memStream).ReadToEnd();
                memStream.Position = 0;
                await memStream.CopyToAsync(originalBody);
                // By now it is to late, above line sets the value that is going to be returned
                await context.Response.WriteAsync(new BaseResponse() { data = responseBody }.toJson());
            }

        }
        finally
        {
            context.Response.Body = originalBody;
        }
like image 393
Lemex Avatar asked Nov 08 '17 13:11

Lemex


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

In .NET Core 3.1 or .NET 5

  1. Create your response envelope object. Example:

    internal class ResponseEnvelope<T>
    {
      public T Data { set; get; }
      public string ApiVersion { set; get; }
      public string OtherInfoHere { set; get; }
    }
    
  2. Derive a class from ObjectResultExecutor

    internal class ResponseEnvelopeResultExecutor : ObjectResultExecutor
    {
     public ResponseEnvelopeResultExecutor(OutputFormatterSelector formatterSelector, IHttpResponseStreamWriterFactory writerFactory, ILoggerFactory loggerFactory, IOptions<MvcOptions> mvcOptions) : base(formatterSelector, writerFactory, loggerFactory, mvcOptions)
     {
     }
    
     public override Task ExecuteAsync(ActionContext context, ObjectResult result)
     {
         var response = new ResponseEnvelope<object>();
         response.Data = result.Value;
         response.ApiVersion = "v1";
         response.OtherInfoHere = "OtherInfo";
    
         TypeCode typeCode = Type.GetTypeCode(result.Value.GetType());
         if (typeCode == TypeCode.Object)
              result.Value = response;
    
         return base.ExecuteAsync(context, result);
      }
    }
    
  3. Inject into the DI like

    public void ConfigureServices(IServiceCollection services)
     {
         services.AddSingleton<IActionResultExecutor<ObjectResult>, ResponseEnvelopeResultExecutor>();
    

And the responses should have an envelope. This does not work with primitive types.

like image 126
Xavier John Avatar answered Sep 23 '22 04:09

Xavier John


Review the comments to get an understanding of what you can do to wrap the response.

public async Task Invoke(HttpContext context) {
    //Hold on to original body for downstream calls
    Stream originalBody = context.Response.Body;
    try {
        string responseBody = null;
        using (var memStream = new MemoryStream()) {
            //Replace stream for upstream calls.
            context.Response.Body = memStream;
            //continue up the pipeline
            await next(context);
            //back from upstream call.
            //memory stream now hold the response data
            //reset position to read data stored in response stream
            memStream.Position = 0;
            responseBody = new StreamReader(memStream).ReadToEnd();
        }//dispose of previous memory stream.
        //lets convert responseBody to something we can use
        var data = JsonConvert.DeserializeObject(responseBody);
        //create your wrapper response and convert to JSON
        var json = new BaseResponse() { 
            data = data, 
            apiVersion = "1.2",
            otherInfoHere = "here"
        }.toJson();
        //convert json to a stream
        var buffer = Encoding.UTF8.GetBytes(json);
        using(var output = new MemoryStream(buffer)) {
            await output.CopyToAsync(originalBody);
        }//dispose of output stream
    } finally {
        //and finally, reset the stream for downstream calls
        context.Response.Body = originalBody;
    }
} 
like image 31
Nkosi Avatar answered Sep 21 '22 04:09

Nkosi