2

i need to set some response example which have same http Status Code by C#.

i have studied the post
https://blog.rsuter.com/nswag-tutorial-implement-a-custom-operation-processor-to-define-redoc-code-samples/

but i still have no idea.

how can i do ?
please give me some hint ...

// i want to create json , like this.
responses:
        '404':
          description: please , let It worked...
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TestModel'
              examples:
                success :
                  summary: Example of a successful response
                  value:
                    code : 1
                    message : "test message 1"
                success2 :
                  summary: Example of a successful response2
                  value:
                    code : 2
                    message: "test message 2"

update : i use NSwag , like this
i need to let code 404 have two Example response

/// <summary></summary>
/// <remarks></remarks>
/// <response code="200"></response>
/// <response code="404">Message 1</response>
/// <response code="404">Message 2</response>   // <---- error will occur , 
[HttpPost]
[ProducesResponseType(typeof(CreateIdentificationResponse), 200)]
[ProducesResponseType(typeof(ErrorResponse), 404)]
[ProducesResponseType(typeof(ErrorResponse), 404)]
public IActionResult Post(){
}
Ci Ty Chen
  • 41
  • 1
  • 5

2 Answers2

1

i get the answer ~~~

// using
// [ExampleAttribute (nameof(MyError.MyErrorFieldName))]

public class ExampleAttribute : OpenApiOperationProcessorAttribute
{
    public ExampleAttribute(string errorField)
        : base(typeof(ExampleAppender))
    {
        var type = typeof(GeneralError);
        var field = type.GetField(errorField, BindingFlags.Public | BindingFlags.Static);       
        var error = field?.GetValue(null) as IMyError;
        Parameters = new object[] { error };
    }

    private class ExampleAppender : IOperationProcessor
    {
        private readonly IMyError _error;
        public ExampleAppender(IMyError error)
        {
            _error = error ?? throw new ArgumentNullException(nameof(error));
        }

        public bool Process(OperationProcessorContext context)
        {
            var openApiResponses = context.OperationDescription.Operation.Responses;
            openApiResponses.TryAdd(((int)_error.StatusCode).ToString(), new OpenApiResponse());
            var apiResponse = openApiResponses[((int)_error.StatusCode).ToString()];
            if (!string.IsNullOrEmpty(_error.StatusCode.ToString()))
            {
                apiResponse.Description = _error.StatusCode.ToString();
            }

            apiResponse.Content.TryAdd(MediaTypeNames.Application.Json, new OpenApiMediaType() { Schema = JsonSchema.FromType<MyErrorResponse>() });
            var openApiMediaType = apiResponse.Content[MediaTypeNames.Application.Json];
            openApiMediaType.Examples.TryAdd( 
                _error.Description ?? "",
                new OpenApiExample()
                {
                    Description = _error.Description,
                    Value = new MyErrorResponse(_error.Message)
                });
            return true;
        }
    }
}

follow the OpenApiOperationProcessorAttribute

NSwag Tutorial: Implement a custom operation processor to define ReDoc code samples

Ci Ty Chen
  • 41
  • 1
  • 5
0

You can the SwaggerResponse attribute like this:

[HttpGet("")]
[SwaggerResponse(200, "Myfile content", typeof(MyFile))]
[SwaggerResponse(404, "Could not find file", typeof(MyFile))]
public async Task<IActionResult> YouAction()

It will document 2 possible reponse status codes: 200 and 404. You can apply as many of those attributes as you wish

Jakub Kozera
  • 3,141
  • 1
  • 13
  • 23
  • Sorry about this , but , i can't set the same HttpStatus code , can i ? like this ```C# [SwaggerResponse(404, "Myfile content", typeof(MyFile))] [SwaggerResponse(404, "Could not find file", typeof(MyFile))] ``` – Ci Ty Chen May 19 '20 at 01:03