简体   繁体   English

在Swagger UI上扩展Swagger响应类型

[英]Extend a Swagger Response Type at Swagger UI

I have the following like this below format for Example Value at Swagger UI: 我在Swagger UI的示例值中具有以下格式,如下所示:

{
  "Username": "string",
  "Interest": "string",
  "Position": "string"
}

And here is the following for the Response Body at Swagger UI: 以下是Swagger UI的响应正文:

{
  "ErrorCode": "0",
  "ErrorMessage": "Success.",
  "Result": [
    {
      "Username": "Test",
      "Interest": "Test",
      "Position": "Test"
    }
  ]
}

My question is, how can I make the Example Value at Swagger UI to be like the Response Body at Swagger UI? 我的问题是,如何使Swagger UI的Example Value像Swagger UI的Response Body

Here is the code that I am using: 这是我正在使用的代码:

Model class: 型号类别:

public class ActionResultExtended
{
   public string ErrorCode { get; set; }
   public string ErrorMessage { get; set; }
   public object Result { get; set; }
}

public class User
{
   public string Username { get; set; }
   public string Interest { get; set; }
   public string Position { get; set; }
}

Controller class: 控制器类:

[ResponseType(typeof(User))] // This is where the Example Value comes from
public HttpResponseMessage GetUser()
{
   var userModel = new User
   {
       Username = "Test",
       Interest = "Test",
       Position = "Test"
   };

   var response = new ActionResultExtended()
   {
       ErrorCode = "0",
       ErrorMessage = "Success.",
       Result = userModel
   };

   return Request.CreateResponse(HttpStatusCode.OK, response);
}

I have tried the following, but it couldn't work as expected. 我已经尝试了以下方法,但无法按预期工作。

  • [ResponseType(typeof(ActionResultExtended))] [的responseType(typeof运算(ActionResultExtended))]

How can I extend the ResponseType attribute from Web API? 如何从Web API扩展ResponseType属性 So that I can make it like the Response Body instead of the Example Value at Swagger UI. 这样我就可以使其像响应正文一样,而不是Swagger UI上的Example值

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

I have solved it by modifying my model class like this: 我已经通过修改我的模型类来解决了这个问题:

Model class: 型号类别:

public class ActionResultExtended
{
   public string ErrorCode { get; set; }
   public string ErrorMessage { get; set; }
   public User Result { get; set; }
}

public class User
{
   public string Username { get; set; }
   public string Interest { get; set; }
   public string Position { get; set; }
}

And from the ResponseType attribute set it like this: 然后从ResponseType属性中进行如下设置:

[ResponseType(typeof(ActionResultExtended))]

This way, the Example Value in Swagger UI will be same like Response Body in Swagger UI: 这样,Swagger UI中的Example值将与Swagger UI中的Response Body相同:

{
  "ErrorCode": "0",
  "ErrorMessage": "Success.",
  "Result": [
    {
      "Username": "Test",
      "Interest": "Test",
      "Position": "Test"
    }
  ]
}

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM