Reputation: 1706
I am using asp.net core 3.1 with Swashbuckle 5.6. I am using a common class ApiResponse to standardize the response structure. So for both http status codes 404 and 500, my response structure will use same class.
But in the generated swagger documentation, I want to provide different examples for different response codes. If I use typeof(ApiResponse) with either ProducesResponseType or SwaggerResponse, it will end up showing same "Example value" for both 404 and 500 status codes. I tried providing sample in the XML documentation. But that does not come with schema.
ApiResponse class structure is same as that used in below link. https://www.devtrends.co.uk/blog/handling-errors-in-asp.net-core-web-api
public class ApiResponse
{
public int StatusCode { get; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; }
public ApiResponse(int statusCode, string message = null)
{
StatusCode = statusCode;
Message = message ?? GetDefaultMessageForStatusCode(statusCode);
}
private static string GetDefaultMessageForStatusCode(int statusCode)
{
switch (statusCode)
{
...
case 404:
return "Resource not found";
case 500:
return "An unhandled error occurred";
default:
return null;
}
}
}
Both statusCode and Message will be different for 404 and 500.
I have another similar issue with Ok Response also. By using generics, I am able to get proper example for class type. But for status code and Message, I am unable to provide specific values.
public class ApiResponseOk<T> : ApiResponse
{
public T Result { get; }
public ApiResponseOk()
{
}
public ApiResponseOk(T result, string message = null)
: base(200, message)
{
Result = result;
}
}
Please let me know how can I provide separate examples when using same type for response.
Thanks!
Upvotes: 0
Views: 1282