Rocco
Rocco
CC#
Created by Rocco on 12/2/2023 in #help
Custom 400 return type (application/fhir+xml)
Currently working on an API that has to be FHIR compliant. FHIR has it's own conventions for dealing with for example a 400. I wrote a middleware to handle with these. It works fine for 401,403 and 404 errors. However as soon as I attempt this on a 400 I get this exception:
System.InvalidOperationException: Headers are read-only, response has already started.
System.InvalidOperationException: Headers are read-only, response has already started.
The code used to write the custom error to the response:
if (context.Request.Headers.Accept.Contains("application/fhir+xml"))
{
var serializer = new BaseFhirXmlPocoSerializer(FhirRelease.STU3);
var xml = serializer.SerializeToString(operationOutcome);
context.Response.ContentType = "application/fhir+xml";
await context.Response.WriteAsync(xml, Encoding.UTF8);
return;
}
if (context.Request.Headers.Accept.Contains("application/fhir+xml"))
{
var serializer = new BaseFhirXmlPocoSerializer(FhirRelease.STU3);
var xml = serializer.SerializeToString(operationOutcome);
context.Response.ContentType = "application/fhir+xml";
await context.Response.WriteAsync(xml, Encoding.UTF8);
return;
}
This is the same code in the same loccation that also handles the 404 errors. And for those it works perfect. It seems ASP starts writing the instant a controller method returns a "BadRequest". How do I stop that behaviour?
10 replies