我正在custom filter
中编写Web API
,并且我想在ActionExecutedContext
方法内修改OnActionExecuted
的结果。
当OkObjectResult
返回action method
时,结果类型为IActionResult
。
public void OnActionExecuted(ActionExecutedContext context)
{
var myResult = context.Result;
//Type of myResult is OkObjectResult
}
因此,在这里如何将OkObjectResult
转换为模型Object
,以便可以使用properties
并操纵值。
赞赏任何建议。
答案 0 :(得分:1)
OkObjectResult的“ Value”属性返回Object。您可以修改对象的属性,甚至可以用新属性替换它。希望这对您有用。如果是这样,请将其标记为答案。
示例代码:
public class Student
{
public string Name { get; set; }
}
[ApiController]
public class TestController : ControllerBase
{
[HttpGet, Route("api/Test/GetString")]
[SampleActionFilter]
public ActionResult<Student> GetString(string name)
{
if(name.StartsWith("s"))
{
return Ok(new Student{ Name = $"This is data {name}" });
}
else
{
return Ok(new Student { Name = $"No Name" });
}
}
}
public class SampleActionFilterAttribute : TypeFilterAttribute
{
public SampleActionFilterAttribute() :
base(typeof(SampleActionFilterImpl))
{
}
private class SampleActionFilterImpl : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// perform some business logic work
}
public void OnActionExecuted(ActionExecutedContext context)
{
// perform some business logic work
var myResult = (OkObjectResult)context.Result;
//Add type checking here... sample code only
//Modiy object values
try
{
Student myVal = (Student)myResult.Value;
myVal.Name = "Johnny";
}
catch { }
}
}
}