从枚举中Swagger预定义的返回类型值

时间:2021-02-20 19:35:48

I need to be able to tell Swagger API documentation that a certain API will return a subset of certain enum.

我需要能够告诉Swagger API文档,某个API将返回某个枚举的子集。

Imagine I have an enum UserType { User_Not_Found, User_Blocked, User_Duplicated, User_Active ...and so on }.

想象一下,我有一个枚举UserType {User_Not_Found,User_Blocked,User_Duplicated,User_Active ......等等}。

One api/users/search might return the user FullName in case it finds a match or "User_Not_Found" in case it doesn't.

一个api / users / search可能会在找到匹配时返回用户FullName,如果不匹配则返回“User_Not_Found”。

return Request.CreateResponse(
       success ? HttpStatusCode.OK : HttpStatusCode.BadRequest, 
       success ? fullName : UserType.User_Not_Found.ToString());

Question: how do I tell swagger that on this specific API the return might return either a fullname if match is found or a "User_Not_Found" if match is not found?

问题:如何告诉swagger在此特定API上,如果找到匹配,则返回可能返回全名,如果未找到匹配,则返回“User_Not_Found”?

1 个解决方案

#1


1  

What you want to do is pretty much like having a regular method return 2 different types based on its execution. This is not possible.

你想要做的就是让常规方法根据其执行返回2种不同的类型。这不可能。

I think you should return the user with a HttpStatusCode.OK if the user is found, else return a custom exception wrapped in the response with HttpStatusCode 401, 403 or 404 (based on what you want). This was you can document the exceptions and that can be reflected in the Swagger UI. However this does not reflect the Enum in the swagger.json.

我认为如果找到用户,你应该使用HttpStatusCode.OK返回用户,否则返回包含在响应中的自定义异常,包括HttpStatusCode 401,403或404(基于你想要的)。这是您可以记录异常,并且可以反映在Swagger UI中。然而,这并不反映swagger.json中的Enum。

    try
    {
        if (isUserFound)
        {
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        throw new UserNotFoundException("User was not found");
    }
    catch (UserNotFoundException ex)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound, ex);
    }

#1


1  

What you want to do is pretty much like having a regular method return 2 different types based on its execution. This is not possible.

你想要做的就是让常规方法根据其执行返回2种不同的类型。这不可能。

I think you should return the user with a HttpStatusCode.OK if the user is found, else return a custom exception wrapped in the response with HttpStatusCode 401, 403 or 404 (based on what you want). This was you can document the exceptions and that can be reflected in the Swagger UI. However this does not reflect the Enum in the swagger.json.

我认为如果找到用户,你应该使用HttpStatusCode.OK返回用户,否则返回包含在响应中的自定义异常,包括HttpStatusCode 401,403或404(基于你想要的)。这是您可以记录异常,并且可以反映在Swagger UI中。然而,这并不反映swagger.json中的Enum。

    try
    {
        if (isUserFound)
        {
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        throw new UserNotFoundException("User was not found");
    }
    catch (UserNotFoundException ex)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound, ex);
    }