Created
October 3, 2019 12:35
-
-
Save chsami/6330e26b8878eb3474bd9558fcda232c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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