如果您从基类NegotitatedContentResult<T> 继承,如上所述,并且您不需要转换您的content(例如,您只想返回一个字符串),那么 您不需要覆盖ExecuteAsync 方法。
您需要做的就是提供一个适当的类型定义和一个构造函数,告诉基础返回哪个 HTTP 状态代码。其他一切正常。
以下是NotFound 和InternalServerError 的示例:
public class NotFoundNegotiatedContentResult : NegotiatedContentResult<string>
{
public NotFoundNegotiatedContentResult(string content, ApiController controller)
: base(HttpStatusCode.NotFound, content, controller) { }
}
public class InternalServerErrorNegotiatedContentResult : NegotiatedContentResult<string>
{
public InternalServerErrorNegotiatedContentResult(string content, ApiController controller)
: base(HttpStatusCode.InternalServerError, content, controller) { }
}
然后您可以为ApiController 创建相应的扩展方法(如果有的话,也可以在基类中进行):
public static NotFoundNegotiatedContentResult NotFound(this ApiController controller, string message)
{
return new NotFoundNegotiatedContentResult(message, controller);
}
public static InternalServerErrorNegotiatedContentResult InternalServerError(this ApiController controller, string message)
{
return new InternalServerErrorNegotiatedContentResult(message, controller);
}
然后它们就像内置方法一样工作。您可以调用现有的NotFound(),也可以调用新的自定义NotFound(myErrorMessage)。
当然,如果需要,您可以摆脱自定义类型定义中的“硬编码”字符串类型并保留其通用性,但是您可能不得不担心@ 987654332@ 的东西,取决于你的 <T> 实际上是什么。
您可以查看source code 的NegotiatedContentResult<T> 以了解它的所有功能。没什么大不了的。