示例#1
0
        /// <inheritdoc />
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            HttpResponse          response = context.HttpContext.Response;
            ActionValidationModel model    = GetModel(context.ActionDescriptor, context.HttpContext.RequestServices);

            MemoryStream buffer        = null;
            Stream       initialStream = null;

            if (model.BufferResponse)
            {
                buffer = new MemoryStream();

                //replace the context response with our buffer
                initialStream = response.Body;
                response.Body = buffer;
            }

            //invoke the rest of the pipeline
            await next();

            if (model.BufferResponse)
            {
                Debug.Assert(buffer != null);

                //reset the buffer and read out the contents
                buffer.Seek(0, SeekOrigin.Begin);

                IList <ValidationError> validationErrors = null;

                if (response.ContentType != null &&
                    (response.ContentType.StartsWith(Constants.ContentTypes.ApplicationJson, StringComparison.Ordinal) || response.ContentType.StartsWith(Constants.ContentTypes.TextJson, StringComparison.Ordinal)))
                {
                    ResponseTypeModel responseTypeModel = model.ResponseTypes.SingleOrDefault(r => r.StatusCode == response.StatusCode);

                    if (responseTypeModel != null)
                    {
                        JSchema responseSchema = SchemaGenerator.GetGeneratedSchema(responseTypeModel.Type);

                        validationErrors = ValidationHelper.Validate(buffer, responseSchema);

                        //reset to start of stream
                        buffer.Seek(0, SeekOrigin.Begin);
                    }
                }

                //copy our content to the original stream and put it back
                await buffer.CopyToAsync(initialStream);

                response.Body = initialStream;

                if (validationErrors != null && validationErrors.Count > 0)
                {
                    throw JSchemaValidationErrorsException.Create(validationErrors);
                }
            }
        }