[英]ASP.Net Core Web API Actions returning anonymous types
我正在使用 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.