Tuf*_*and 2 custom-action-filter onactionexecuted asp.net-core-webapi asp.net-core-2.1
我正在写custom filter我的内容Web API,我想修改方法ActionExecutedContext内部的结果OnActionExecuted。
我得到的结果类型与返回的OkObjectResult一样。action methodIActionResult
public void OnActionExecuted(ActionExecutedContext context)
{
var myResult = context.Result;
//Type of myResult is OkObjectResult
}
Run Code Online (Sandbox Code Playgroud)
那么这里我如何将其转换OkObjectResult为我的模型Object,以便我可以使用properties并操作这些值。
感谢任何建议。
OkObjectResult 的“Value”属性返回对象。您可以修改对象的属性,甚至可以用新对象替换它。希望这对你有用。如果是,请将其标记为答案。
示例代码:
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 { }
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6972 次 |
| 最近记录: |