I'm working on an ASP.NET 2.2 Web API project which uses a wrapper for producing consistent responses. After some searching, I found that the team followed the implementation from the article, “A Custom Wrapper For Managing Exceptions And Consistent Responses”.
This works as expected. Now we are planning to upgrade to ASP.NET Core 3.1. After upgrading, this doesn't work as expected. I think it was due to breaking changes between ASP.NET Core 2.2 and 3.1. I fixed all these following Microsoft’s Migrate from ASP.NET Core 2.2 to 3.0 guide.
Now my JSON response from the API breaks.
Here is the code that gets executed when the response is successful:
private static Task HandleSuccessRequestAsync(HttpContext context, object body, int code)
{
context.Response.ContentType = "application/json";
string jsonString, bodyText = string.Empty;
APIResponse apiResponse = null;
if (!body.ToString().IsValidJson())
bodyText = JsonConvert.SerializeObject(body);
else
bodyText = body.ToString();
dynamic bodyContent = JsonConvert.DeserializeObject<dynamic>(bodyText);
Type type;
type = bodyContent?.GetType();
if (type.Equals(typeof(Newtonsoft.Json.Linq.JObject)))
{
apiResponse = JsonConvert.DeserializeObject<APIResponse>(bodyText);
if (apiResponse.StatusCode != code)
jsonString = JsonConvert.SerializeObject(apiResponse);
else if (apiResponse.Result != null)
jsonString = JsonConvert.SerializeObject(apiResponse);
else
{
apiResponse = new APIResponse(code, ResponseMessageEnum.Success.GetDescription(), bodyContent, null);
jsonString = JsonConvert.SerializeObject(apiResponse);
}
}
else
{
apiResponse = new APIResponse(code, ResponseMessageEnum.Success.GetDescription(), bodyContent, null);
jsonString = JsonConvert.SerializeObject(apiResponse);
}
return context.Response.WriteAsync(jsonString);
}
I debugged until it hit the return context.Response.WriteAsync(jsonString); inside the HandleSuccessRequestAsync() method. Everything is fine. But the JSON response breaks.
Expected Response:
{
"Version": "1.0.0.0",
"StatusCode": 200,
"Message": "Request successful.",
"Result": [
"value1",
"value2"
]
}
Actual Response:
{
"Version": "1.0.0.0",
"StatusCode": 200,
"Message": "Request successful.",
"Result":
Please assist me on where I'm going wrong? Is this because of theASP.NET Core 3.1 upgrade?
Resultin json has no data? According to your provided link and the migration document , my 3.1 project which is migrated from 2.2 project worked well ,and theResulthas the value.If you want the community review and debug the code ,could you share a complete demo that can reproduce the issue ?returnand the user? Or do you mean that everything works fine, except that the deserialization is returning the truncated JSON?