C# WebAPI Stream content

Date: 2018-01-30
namespace Example {
    public class ExampleApiController : ApiController {

        [HttpGet]
        [Route ("api/content-stream/example")]
        public HttpResponseMessage GetContentStream () {
            try {
                var response = new HttpResponseMessage (HttpStatusCode.OK);
                response.Content = new PushStreamContent (
                    async (outputStream, httpContext, transportContext) => {
                        try {
                            Stream memoryStream = new MemoryStream ("data from a custom stream");
                            memoryStream.Position = 0;
                            await memoryStream.CopyToAsync (outputStream);
                            memoryStream.Flush ();
                            memoryStream.Close ();
                        } finally {
                            // Close output stream as we are done
                            outputStream.Flush ();
                            outputStream.Close ();
                        }
                    },
                    "application/octet-stream"
                );

                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") {
                    FileName = "data.txt"
                };
                return response;
            } catch (Exception ex) {
                Log.Error (ex);
                return ResponseHelper.FromException (Request, ex);
            }
        }
    }

    public class TaskValidationResult {
        public TaskValidationResult () {

        }

        public TaskValidationResult (string message, string property = null, object target = null) {
            Message = message;
            Property = property;
            Target = target;
        }

        public string Message;
        public string Property;
        public object Target;
    }

    public class TaskResult<T> {
        public bool Success {
            get {
                return !ValidationResults.Any ();
            }
        }

        public T Result;
        public int TotalResultCount = 0;
        public IList<TaskValidationResult> ValidationResults = new List<TaskValidationResult> ();
    }

    public class ResponseHelper {
        public static HttpResponseMessage FromSuccess<T> (HttpRequestMessage request, T result, HttpStatusCode successCode = HttpStatusCode.OK) {
            return request.CreateResponse (successCode, result, "application/json");
        }

        public static HttpResponseMessage FromFail (HttpRequestMessage request, string message, HttpStatusCode failCode = HttpStatusCode.BadRequest) {
            var validationResults = new List<TaskValidationResult> {
            new TaskValidationResult (message)
            };
            return request.CreateResponse (failCode, validationResults, "application/json");
        }

        public static HttpResponseMessage FromFail (HttpRequestMessage request, IEnumerable<TaskValidationResult> validationResults, HttpStatusCode failCode = HttpStatusCode.BadRequest) {
            return request.CreateResponse (failCode, validationResults, "application/json");
        }

        public static HttpResponseMessage FromTaskResult<T> (HttpRequestMessage request, TaskResult<T> result, HttpStatusCode successCode = HttpStatusCode.OK, HttpStatusCode failCode = HttpStatusCode.BadRequest) {
            if (result.Success) {
                var response = request.CreateResponse (successCode, result.Result, "application/json");
                response.Headers.Add ("X-TotalCount", result.TotalResultCount.ToString ());
                return response;
            } else {
                return request.CreateResponse (failCode, result.ValidationResults);
            }
        }

        public static HttpResponseMessage FromException (HttpRequestMessage request, Exception ex, HttpStatusCode statusCode = HttpStatusCode.InternalServerError) {
#if DEBUG
            return request.CreateResponse (statusCode, ex, "application/json");
#else
            return request.CreateResponse (statusCode, "");
#endif
        }
    }
}
8150cookie-checkC# WebAPI Stream content