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

dim*_*its 6 .net asp.net-web-api swagger swagger-ui swashbuckle

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

    [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");
    }
Run Code Online (Sandbox Code Playgroud)

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 =>
                    {

                    });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是现在当我运行项目和 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;
    }
Run Code Online (Sandbox Code Playgroud)

https://prnt.sc/o7wp4d

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

str*_*t01 7

您可以通过属性声明响应类型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");
}
Run Code Online (Sandbox Code Playgroud)