![](/img/trans.png)
[英]How is ASP.NET Core able to convert any type to ActionResult<T> return type of controller actions?
[英]ASP.net Core API returning ActionResult<T> not enforcing return type
如果 API 返回ActionResult<T>
,则不会进行编译或运行时检查以确保返回的数据类型与声明的相同。
例如:
public ActionResult<Dog> GetCat()
{
var cat = new Cat("Moggy");
return Ok(cat);
}
这将编译、运行并返回 Cat object。
我遇到的问题是 OpenAPI 定义(Swagger/Swashbuckle)是从方法上声明的类型派生的。 这意味着 OpenAPI 定义可能与代码不同步,并且没有明显的方法可以找到这些实例。
在给出的示例中,我的 API 文档会告诉人们,这个 API 返回的是一只狗,而实际上它返回的是一只猫。
有没有办法在编译时强制执行返回类型,或者在运行时失败?
那是因为您返回的类型OkObjectResult
继承了ActionResult
。 返回的子 class 不会影响父 class 编译。这是设计使然。
有关这两个 class 的更多详细信息,您可以参考以下源代码:
1. Ok
方法返回OkObjectResult
的类型:
// Summary:
// A base class for an MVC controller without view support.
[Controller]
public abstract class ControllerBase
{
// Summary:
// Creates an Microsoft.AspNetCore.Mvc.OkObjectResult object that produces an Microsoft.AspNetCore.Http.StatusCodes.Status200OK
// response.
//
// Parameters:
// value:
// The content value to format in the entity body.
//
// Returns:
// The created Microsoft.AspNetCore.Mvc.OkObjectResult for the response.
[NonAction]
public virtual OkObjectResult Ok([ActionResultObjectValueAttribute] object value);
2. OkObjectResult
继承ObjectResult
:
//
// Summary:
// An Microsoft.AspNetCore.Mvc.ObjectResult that when executed performs content
// negotiation, formats the entity body, and will produce a Microsoft.AspNetCore.Http.StatusCodes.Status200OK
// response if negotiation and formatting succeed.
[DefaultStatusCode(200)]
public class OkObjectResult : ObjectResult
{
//
// Summary:
// Initializes a new instance of the Microsoft.AspNetCore.Mvc.OkObjectResult class.
//
// Parameters:
// value:
// The content to format into the entity body.
public OkObjectResult(object value);
}
ObjectResult
继承ActionResult
:
public class ObjectResult : ActionResult, IStatusCodeActionResult, IActionResult
{
public ObjectResult(object value);
//..
}
有没有办法在编译时强制执行返回类型,或者在运行时失败?
ActionResult<T>
使您能够返回派生自ActionResult
的类型或返回特定类型。
要强制编译错误,您可以只返回特定类型的 cat。当您将Dog
更改为Cat
时,您会看到错误消息消失:
public ActionResult<Dog> GetCat()
{
var cat = new Cat("Moggy");
return cat;
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.