Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have http response wrapper that rewrite response and suppose to send response like below
{"Version":"1.0.0.0","StatusCode":200,"Message":"Success","Result":[{"code":"465","name":"fasdfsdfsd","systemkey":"AAAAAACL","createdby":"RM      ","createddt":"2016-05-24T00:00:00","createdti":"20:12","lasteditby":"RM      ","lasteditdt":"2016-05-24T00:00:00","lasteditti":"20:12","notallowed":null,"mark":" "}]}


but response is truncate at then end
{"Version":"1.0.0.0","StatusCode":200,"Message":"Success","Result":[{"code":"sds","name":"fsdafsdfsd","systemkey":"AAAAAABT","createdby":"RM      ","createddt":"2016-04-25T00:00:00","createdti":"16:14","lasteditby":"RM      ","lasteditdt":"2016-0


how can i fix it?

What I have tried:

below is code
C#
[DataContract]
    public class APIResponse
    {
        [DataMember]
        public string Version { get; set; }

        [DataMember]
        public int StatusCode { get; set; }

        [DataMember]
        public string Message { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public ApiError ResponseException { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public object Result { get; set; }

        public APIResponse(int statusCode, string message = "", object result = null, ApiError apiError = null, string apiVersion = "1.0.0.0")
        {
            this.StatusCode = statusCode;
            this.Message = message;
            this.Result = result;
            this.ResponseException = apiError;
            this.Version = apiVersion;
        }
    }

C#
public class APIResponseMiddleware
   {
       private readonly RequestDelegate _next;

       public APIResponseMiddleware(RequestDelegate next)
       {
           _next = next;
       }

       public async Task Invoke(HttpContext context)
       {
           if (IsSwagger(context))
               await this._next(context);
           else
           {
               var originalBodyStream = context.Response.Body;

               using (var responseBody = new MemoryStream())
               {
                   context.Response.Body = responseBody;

                   try
                   {
                       await _next.Invoke(context);

                       if (context.Response.StatusCode == (int)HttpStatusCode.OK)
                       {
                           var body = await FormatResponse(context.Response);
                           await HandleSuccessRequestAsync(context, body, context.Response.StatusCode);

                       }
                       else
                       {
                           await HandleNotSuccessRequestAsync(context, context.Response.StatusCode);
                       }
                   }
                   catch (System.Exception ex)
                   {
                       await HandleExceptionAsync(context, ex);
                   }
                   finally
                   {
                       responseBody.Seek(0, SeekOrigin.Begin);
                       await responseBody.CopyToAsync(originalBodyStream);
                   }
               }
           }

       }

C#
private static Task HandleSuccessRequestAsync(HttpContext context, object body, int code)
        {
            context.Response.ContentType = "application/json";
            string jsonString, bodyText = string.Empty;
            APIResponse apiResponse = null;


            if (!body.ToString().IsValidJson())
                bodyText = JsonConvert.SerializeObject(body);
            else
                bodyText = body.ToString();

            dynamic bodyContent = JsonConvert.DeserializeObject<dynamic>(bodyText);
            Type type;

            type = bodyContent?.GetType();

            if (type.Equals(typeof(Newtonsoft.Json.Linq.JObject)))
            {
                apiResponse = JsonConvert.DeserializeObject<APIResponse>(bodyText);
                if (apiResponse.StatusCode != code)
                    jsonString = JsonConvert.SerializeObject(apiResponse);
                else if (apiResponse.Result != null)
                    jsonString = JsonConvert.SerializeObject(apiResponse);
                else
                {
                    apiResponse = new APIResponse(code, ResponseMessageEnum.Success.GetDescription(), bodyContent, null);
                    jsonString = JsonConvert.SerializeObject(apiResponse);
                }
            }
            else
            {
                apiResponse = new APIResponse(code, ResponseMessageEnum.Success.GetDescription(), bodyContent, null);
                jsonString = JsonConvert.SerializeObject(apiResponse);
            }

            return context.Response.WriteAsync(jsonString);
        }

        private async Task<string> FormatResponse(HttpResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);
            var plainBodyText = await new StreamReader(response.Body).ReadToEndAsync();
            response.Body.Seek(0, SeekOrigin.Begin);

            return plainBodyText;
        }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900