หากคุณรับช่วงจากฐาน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)ก็ได้
และแน่นอนคุณสามารถกำจัดประเภทสตริง "ฮาร์ดโค้ด" ในคำจำกัดความประเภทที่กำหนดเองและปล่อยให้เป็นแบบทั่วไปได้หากคุณต้องการ แต่คุณอาจต้องกังวลเกี่ยวกับExecuteAsyncสิ่งต่างๆขึ้นอยู่กับสิ่งที่คุณ<T>เป็นจริง
คุณสามารถดูมากกว่ารหัสที่มาสำหรับการNegotiatedContentResult<T>ที่จะเห็นทั้งหมดมันไม่ มีไม่มากนัก