Skip to content

Instantly share code, notes, and snippets.

@chsami
Created October 3, 2019 12:35
Show Gist options
  • Save chsami/6330e26b8878eb3474bd9558fcda232c to your computer and use it in GitHub Desktop.
Save chsami/6330e26b8878eb3474bd9558fcda232c to your computer and use it in GitHub Desktop.
public class JsonStatusCodeMiddleWare
{
private readonly RequestDelegate _next;
public JsonStatusCodeMiddleWare(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Response.StatusCode == (int)HttpStatusCode.OK)
{
await _next(context);
return;
}
context.Response.ContentType = "application/json";
string jsonString = "";
switch (context.Response.StatusCode)
{
case (int) HttpStatusCode.NotFound:
jsonString = JsonConvert.SerializeObject(new ApiError()
{
Success = false,
ErrorKey = context.Response.StatusCode.ToString(),
Message = "Resource does not exist on the server!"
});
break;
case (int)HttpStatusCode.Unauthorized:
jsonString = JsonConvert.SerializeObject(new ApiError()
{
Success = false,
ErrorKey = context.Response.StatusCode.ToString(),
Message = "Requested resource requires authentication!"
});
break;
default:
break;
}
await context.Response.WriteAsync(jsonString, Encoding.UTF8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment