c#, web api, swashbuckler/swagger

2019-07-22 12:15发布

问题:

This is my first web api, first web app, and first time Ive used swagger via swashbuckler. I'm using TPH for my equipment db table.
For example, I have base class called equipment with several child classes inherited from equipment. (This isnt real code so Ive not put in all the publics etc)
As I sorta expect, the model description when I run swagger in my browser, just returns the model for the equipment class
I've googled how to show all possible models but can't understand the replies as they don't relate to c#, or api controllers using comments for documentation, or they're written for people who understand this more than I do.
is anybody able to post an example, or point me to a beginner tutorial please, on how to get swagger display all possible models. I've had to write several different api calls to get around this, just so the models are shown.
thanks

class equipment
{
  public int id{get;set;}
  public int foo{get;set;}
  public int bar{get;set;}
}

class bucket : equipment
{      
  public int booboo{get;set;}
}
class mop : equipment
{
  public int lala{get;set;}
}


// equipmentcontroller class get function

/// <summary>
/// Returns a piece of equipment.<br/>
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Route(@"{id:int}"), ResponseType(typeof(equipment))]
public IHttpActionResult GetMop(int id)
{
  return result != null ? (IHttpActionResult)Ok(GetMop[id]) : NotFound();
}

回答1:

What you're suggesting isn't possible. In Swagger, the definition of responses for an operation is basically a mapping of different HTTP status codes to specific response objects. (Have a look at http://swagger.io/specification/#responsesObject)

It's not going to be possible for you to represent that a 200 OK for an operation could either return a response representing a mop or a response representing a bucket.

You mention "I've had to write several different api calls to get around this, just so the models are shown.", this is what I'd expect from a RESTful API. Different kinds of resources are handled by different endpoints.