ASP.Net Core Web API操作返回匿名类型



我正在使用ASP。Net Core 5创建一个web API。我使用像这样的控制器

[Route("[controller]")]
[ApiController]
public class User : ControllerBase
{
...
public async Task<ActionResult<User>> GetUserByID(int id)
{
...
}
...
}

这很好,但意味着我会继续为返回的数据创建定义的类型化类。我有时对返回匿名类型而不是特定类型感兴趣,这可能吗?

您可以使用IActionResult。例如:

[HttpGet, Route("getUserById/{id}")]
public async Task<IActionResult> GetUserByID(int id)
{
var data = await Something.GetUserAsync(id);
return Ok(new
{
thisIsAnonymous = true,
user = data
});
}

有一件事你"可以";要做的是返回一个";字符串";通过将数据序列化为JSON字符串或XML,始终键入。然后对客户进行相应的解释。然而,理想情况下应该考虑使用";ProducesResponseType";特性以及几个内置的帮助器方法,以根据不同的条件生成不同的响应,这样您就可以根据不同的场景返回不同的类型。参见以下示例:

[HttpGet]
[ProducesResponseType(typeof(User), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(User), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<User>> GetUserByID(int id)
{
try
{
User model = await _userService.Get(id);
return Ok(model);
}
catch (ApiAccessException apiException)
{
ApiFailureDetail detail = new ApiFailureDetail { ApiError = apiException.ApiError, TechnicalMessage = apiException.TechnicalMessage, UserFriendlyMessage = apiException.UserFriendlyMessage };
//Serialize the exception
string errorOutput = JsonConvert.SerializeObject(detail);
return Unauthorized(errorOutput);
}
catch (ApiException apiException)
{
ApiFailureDetail detail = new ApiFailureDetail { ApiError = apiException.ApiError, TechnicalMessage = apiException.TechnicalMessage, UserFriendlyMessage = apiException.UserFriendlyMessage };
string errorOutput = JsonConvert.SerializeObject(detail);
return BadRequest(errorOutput);
}
catch (Exception e)
{
ApiFailureDetail detail = new ApiFailureDetail { ApiError = ApiError.InternalError, TechnicalMessage = e.Message, UserFriendlyMessage = "Internal unknown error." };
string errorOutput = JsonConvert.SerializeObject(detail);
return BadRequest(errorOutput);
}
}

最新更新