在Swagger UI

时间:2017-11-22 14:55:43

标签: c# asp.net-web-api swagger

我在Swagger UI中的 示例值 的格式如下:

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

以下是Swagger UI中 Response Body 的以下内容:

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

我的问题是,如何让Swagger UI中的 示例值 响应主体 在Swagger UI?

以下是我正在使用的代码:

模特课程:

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; }
}

控制器类:

[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);
}

我尝试过以下操作,但无法按预期工作。

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

如何从Web API扩展 ResponseType属性 ?因此,我可以在Swagger UI中将其设置为 Response Body ,而不是 示例值

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

我通过修改我的模型类解决了这个问题:

模型类:

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; }
}

ResponseType 属性设置如下:

[ResponseType(typeof(ActionResultExtended))]

这样,Swagger UI中的 示例值 与Swagger UI中的 Response Body 相同:

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

谢谢。