gpt4 book ai didi

.net - 当我返回类型 HttpResponseMessage 时,示例值和模型在 swagger ui 中为空

转载 作者:行者123 更新时间:2023-12-05 02:11:57 25 4
gpt4 key购买 nike

我使用 .net 框架和 nuget 包 Swashbuckle。我有带有方法的 Controller

    [HttpGet]
[ActionName("getProductById")]
public HttpResponseMessage GetProductById([FromUri] int id)
{
Product response = service.GetProductById(id);
if (response != null)
{

return Request.CreateResponse<Product>(HttpStatusCode.OK, response);
}
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
}

SwaggerConfig 是

    [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace ProductsApp
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;

GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "ProductsApp");
})
.EnableSwaggerUi(c =>
{

});
}
}
}

但是现在当我运行项目和 url localhost:61342/swagger/ui/index 时,我遇到了示例值和模型为空的问题。 https://prnt.sc/o7wlqe

当我修改方法只返回产品就可以了。

    [HttpGet]
[ActionName("getProductById")]
public Product GetProductById([FromUri] int id)
{
Product response = service.GetProductById(id);
return response;
}

https://prnt.sc/o7wp4d

我如何结合返回 HttrResponseMessage 并获得示例值和模型?

最佳答案

您可以通过 ResponseTypeAttribute 属性声明响应类型:

[HttpGet]
[ActionName("getProductById")]
[ResponseType(typeof(Product))]
public HttpResponseMessage GetProductById([FromUri] int id)
{
Product response = service.GetProductById(id);
if (response != null)
{

return Request.CreateResponse<Product>(HttpStatusCode.OK, response);
}
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
}

关于.net - 当我返回类型 HttpResponseMessage 时,示例值和模型在 swagger ui 中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com