i create a Action Filter
for custom return context.result
:
public class ResultApi : ActionFilterAttribute
{
private readonly ResposeFormat resposeFormat;
public ResultApi(ResposeFormat resposeFormat)
{
this.resposeFormat = resposeFormat;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
resposeFormat.ContextResult(context);
base.OnResultExecuting(context);
}
}
i using the strategy pattern for change result format :
public abstract class ResposeFormat
{
public abstract void ContextResult(ResultExecutingContext context);
}
and these are for implement the result Type :
public abstract class OkResultFormatter : ResposeFormat
{
public override void ContextResult(ResultExecutingContext context)
{
if (context.Result is OkResult okResult)
context.Result = new JsonResult(new ReturnResult(true, StatusCode.Success)) { StatusCode = okResult.StatusCode };
}
}
BadRequest :
public abstract class BadRquestObjectresultFormatter : ResposeFormat
{
public override void ContextResult(ResultExecutingContext context)
{
if (context.Result is BadRequestObjectResult badRequestObjectResult)
{
var message = badRequestObjectResult.Value.ToString();
if (badRequestObjectResult.Value is SerializableError errors)
{
var errorMessages = errors.SelectMany(p => (string[])p.Value).Distinct();
message = string.Join(" | ", errorMessages);
}
context.Result = new JsonResult(new ReturnResult(false, StatusCode.BadRequest, message)) { StatusCode = badRequestObjectResult.StatusCode };
}
}
}
i want when pass the context
to the resposeFormat.ContextResult(context);
it find the type of request and use the OkResultFormatter
or BadRquestObjectresultFormatter
.
how can i do this issue ????
Aucun commentaire:
Enregistrer un commentaire