Search code examples
swaggerasp.net-core-webapi

How to set up swagger example value on ASP.NET Core 8 Web API project


Is there a way to set up the content of "Example value" of Swagger to an ASP.NET Core 8 Web API project?

This the XML configuration file:

<member name="M:BD.User.DWA.Services.BDUserController.GetDynamicTokenExt(Newtonsoft.Json.Linq.JObject)">
     <summary>
     Il metodo restituisce il token criptato, moduli abilitati in chiaro, risposta di accounting a partire da userKey, appId, fingerPrint, data.
     </summary>
     <param name="oInputParams">Oggetto JSON con i parametri di input</param>     
     <remarks>
     Esempio di input
     
         POST /api/BD.User.BDUserServiceREST.svc/GetDynamicTokenExt
         {
             "parameters":{
                 "userKey": "as_smart01",
                 "appId": "4241",
                 "isSIACUser": false,
                 "data": {
                     "environment": "ON",
                     "modules": [
                         "1"
                     ],
                     "accountType": 0
                 }
             }
         }
         
     </remarks>
     <returns></returns>
 </member>

Swagger console:

enter image description here


Solution

  • Yes, you can do in code implementing IExamplesProvider from Swashbuckle.AspNetCore.Filters

    A sample from here https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters/blob/master/README.md#how-to-use---request-examples

    [HttpPost]
    public async Task<IHttpActionResult> DeliveryOptionsForAddress([FromBody]DeliveryOptionsSearchModel search)
    

    can be written for a sample as

    public class DeliveryOptionsSearchModelExample : IExamplesProvider<DeliveryOptionsSearchModel>
    {
        public DeliveryOptionsSearchModel GetExamples()
        {
            return new DeliveryOptionsSearchModel
            {
                Lang = "en-GB",
                Currency = "GBP",
                Address = new AddressModel
                {
                    Address1 = "1 Gwalior Road",
                    Locality = "London",
                    Country = "GB",
                    PostalCode = "SW15 1NP"
                }
            };
        }