Exemplo n.º 1
0
        public override System.Threading.Tasks.Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }

            XmlWriterSettings settings = new XmlWriterSettings
            {
                Encoding           = new UTF8Encoding(false),
                OmitXmlDeclaration = true,
                Async           = true,
                CloseOutput     = true,
                Indent          = true,
                NewLineHandling = NewLineHandling.Entitize,
                IndentChars     = "  "
            };

            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Body, settings))
            {
                R4Rest.SummaryType   R4SummaryType   = R4Rest.SummaryType.False;
                Stu3Rest.SummaryType Stu3SummaryType = Stu3Rest.SummaryType.False;
                if (context.ObjectType == typeof(R4Model.OperationOutcome))
                {
                    // We will only honor the summary type during serialization of the outcome
                    // if the resource wasn't a stored OpOutcome we are returning
                    R4Model.OperationOutcome resource = (R4Model.OperationOutcome)context.Object;
                    if (string.IsNullOrEmpty(resource.Id) && resource.HasAnnotation <R4Rest.SummaryType>())
                    {
                        R4SummaryType = resource.Annotation <R4Rest.SummaryType>();
                    }
                    new R4Serialization.FhirXmlSerializer().Serialize(resource, writer, R4SummaryType);
                }
                else if (context.ObjectType == typeof(Stu3Model.OperationOutcome))
                {
                    // We will only honor the summary type during serialization of the outcome
                    // if the resource wasn't a stored OpOutcome we are returning
                    Stu3Model.OperationOutcome resource = (Stu3Model.OperationOutcome)context.Object;
                    if (string.IsNullOrEmpty(resource.Id) && resource.HasAnnotation <Stu3Rest.SummaryType>())
                    {
                        Stu3SummaryType = resource.Annotation <Stu3Rest.SummaryType>();
                    }
                    new Stu3Serialization.FhirXmlSerializer().Serialize(resource, writer, Stu3SummaryType);
                }
                else if (typeof(R4Model.Resource).IsAssignableFrom(context.ObjectType))
                {
                    if (context.Object != null)
                    {
                        R4Model.Resource r = (R4Model.Resource)context.Object;
                        if (r.HasAnnotation <R4Rest.SummaryType>())
                        {
                            R4SummaryType = r.Annotation <R4Rest.SummaryType>();
                        }

                        new R4Serialization.FhirXmlSerializer().Serialize(r, writer, R4SummaryType);
                    }
                }
                else if (typeof(Stu3Model.Resource).IsAssignableFrom(context.ObjectType))
                {
                    if (context.Object != null)
                    {
                        Stu3Model.Resource r = (Stu3Model.Resource)context.Object;
                        if (r.HasAnnotation <Stu3Rest.SummaryType>())
                        {
                            Stu3SummaryType = r.Annotation <Stu3Rest.SummaryType>();
                        }
                        new Stu3Serialization.FhirXmlSerializer().Serialize(r, writer, Stu3SummaryType);
                    }
                }
                return(writer.FlushAsync());
            }
        }
Exemplo n.º 2
0
        public override System.Threading.Tasks.Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }

            using (StreamWriter writer = new StreamWriter(context.HttpContext.Response.Body))
            {
                // netcore default is for async only
                var syncIOFeature = context.HttpContext.Features.Get <IHttpBodyControlFeature>();
                if (syncIOFeature != null)
                {
                    syncIOFeature.AllowSynchronousIO = true;
                }

                JsonTextWriter jsonwriter = (JsonTextWriter)SerializationUtil.CreateJsonTextWriter(writer); // This will use the BetterJsonWriter which handles precision correctly
                using (jsonwriter)
                {
                    jsonwriter.ArrayPool  = _charPool;
                    jsonwriter.Formatting = Formatting.Indented; // lets make it pretty

                    R4Rest.SummaryType   R4SummaryType   = R4Rest.SummaryType.False;
                    Stu3Rest.SummaryType Stu3SummaryType = Stu3Rest.SummaryType.False;
                    if (context.ObjectType == typeof(Stu3Model.OperationOutcome))
                    {
                        // We will only honor the summary type during serialization of the outcome
                        // if the resource wasn't a stored OpOutcome we are returning
                        Stu3Model.OperationOutcome resource = (Stu3Model.OperationOutcome)context.Object;
                        if (string.IsNullOrEmpty(resource.Id) && resource.HasAnnotation <Stu3Rest.SummaryType>())
                        {
                            Stu3SummaryType = resource.Annotation <Stu3Rest.SummaryType>();
                        }
                        new Stu3Serialization.FhirJsonSerializer().Serialize(resource, jsonwriter, Stu3SummaryType);
                    }
                    else if (typeof(Stu3Model.Resource).IsAssignableFrom(context.ObjectType))
                    {
                        if (context.Object != null)
                        {
                            Stu3Model.Resource r = (Stu3Model.Resource)context.Object;
                            if (r.HasAnnotation <Stu3Rest.SummaryType>())
                            {
                                Stu3SummaryType = r.Annotation <Stu3Rest.SummaryType>();
                            }
                            new Stu3Serialization.FhirJsonSerializer().Serialize(r, jsonwriter, Stu3SummaryType);
                        }
                    }
                    else if (context.ObjectType == typeof(R4Model.OperationOutcome))
                    {
                        // We will only honor the summary type during serialization of the outcome
                        // if the resource wasn't a stored OpOutcome we are returning
                        R4Model.OperationOutcome resource = (R4Model.OperationOutcome)context.Object;
                        if (string.IsNullOrEmpty(resource.Id) && resource.HasAnnotation <R4Rest.SummaryType>())
                        {
                            R4SummaryType = resource.Annotation <R4Rest.SummaryType>();
                        }
                        new R4Serialization.FhirJsonSerializer().Serialize(resource, jsonwriter, R4SummaryType);
                    }
                    else if (typeof(R4Model.Resource).IsAssignableFrom(context.ObjectType))
                    {
                        if (context.Object != null)
                        {
                            R4Model.Resource r = (R4Model.Resource)context.Object;
                            if (r.HasAnnotation <R4Rest.SummaryType>())
                            {
                                R4SummaryType = r.Annotation <R4Rest.SummaryType>();
                            }
                            new R4Serialization.FhirJsonSerializer().Serialize(r, jsonwriter, R4SummaryType);
                        }
                    }
                    return(writer.FlushAsync());
                }
            }
        }
        private Task HandleExceptionAsync(HttpContext context, Exception exec, ILogger <ErrorHandlingMiddleware> _logger)
        {
            _logger.LogError(exec, exec.Message);
            FhirVersion VersionInUse = GetFhirVersionInUse(context.Request.Path.Value);

            if (exec is FhirException FhirException)
            {
                _logger.LogError(FhirException, "FhirException has been thrown");
                FhirFormatType AcceptFormatType = Bug.Api.ContentFormatters.FhirMediaType.GetFhirFormatTypeFromAcceptHeader(context.Request.Headers.SingleOrDefault(x => x.Key.ToLower(System.Globalization.CultureInfo.CurrentCulture) == "accept").Value);
                switch (VersionInUse)
                {
                case FhirVersion.Stu3:
                {
                    return(Stu3FhirExceptionProcessing(context, FhirException, AcceptFormatType));
                }

                case FhirVersion.R4:
                {
                    return(R4FhirExceptionProcessing(context, FhirException, AcceptFormatType));
                }

                default:
                    throw new ApplicationException($"Unable to resolve which major version of FHIR is in use. Found enum: {VersionInUse.ToString()}");
                }
            }
            else
            {
                string ErrorGuid         = Common.FhirTools.FhirGuidSupport.NewFhirGuid();
                string UsersErrorMessage = string.Empty;
                if (Debugger.IsAttached)
                {
                    UsersErrorMessage = $"{System.Text.Encodings.Web.HtmlEncoder.Default.Encode(exec.ToString())} ->  Server Error log identifier: {ErrorGuid}";
                }
                else
                {
                    UsersErrorMessage = $"An unhanded exception has been thrown. To protect data privacy the exception information has been written to the application log with the error log identifier: {ErrorGuid}";
                }
                _logger.LogError(exec, $"Error log identifier: {ErrorGuid}");
                switch (VersionInUse)
                {
                case FhirVersion.Stu3:
                {
                    Stu3Model.OperationOutcome Stu3OperationOutcomeResult = IOperationOutComeSupportFactory.GetStu3().GetFatal(new string[] { UsersErrorMessage });
                    context.Response.ContentType = Bug.Api.ContentFormatters.FhirMediaType.GetMediaTypeHeaderValue(Stu3OperationOutcomeResult.GetType(), FhirFormatType.xml).Value;
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    return(context.Response.WriteAsync(IStu3SerializationToXml.SerializeToXml(Stu3OperationOutcomeResult)));
                }

                case FhirVersion.R4:
                {
                    R4Model.OperationOutcome R4OperationOutcomeResult = IOperationOutComeSupportFactory.GetR4().GetFatal(new string[] { UsersErrorMessage });
                    context.Response.ContentType = Bug.Api.ContentFormatters.FhirMediaType.GetMediaTypeHeaderValue(R4OperationOutcomeResult.GetType(), FhirFormatType.xml).Value;
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    return(context.Response.WriteAsync(IR4SerializationToXml.SerializeToXml(R4OperationOutcomeResult)));
                }

                default:
                    string msg = $"Unable to resolve which major version of FHIR is in use. Found enum: {VersionInUse.ToString()}";
                    _logger.LogError(msg);
                    throw new ApplicationException(msg);
                }
            }
        }