C
C#7mo ago
Rocco

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?
6 Replies
JP
JP7mo ago
Where does this code live?
Rocco
Rocco7mo ago
Middleware
Rocco
Rocco7mo ago
No description
JP
JP7mo ago
Hm... this looks potentially promising? https://hanson.io/aspnet-setting-cookies-in-middleware/#final-pass they make use of context.Response.OnStarting, not sure if that'd be applicable here also, middleware order can matter, but if what you've show is all your middleware, LGTM on that front
Rocco
Rocco7mo ago
I think this will work thanks It worked! thanks
JP
JP7mo ago
awesome, happy to help!