In our application we are using mediatr and there is a common pattern as follows:
class SomeController
{
public Action Foo(SomeRequest request)
{
var result = Mediatr.Send(request);
if(result == null)
{
return NotFound();
}
return Ok(result);
}
}
This code repeats for every API end point, regardless of the HTTP method.
I read about API conventions but I guess that is about Swagger, API analyser and such.
How can I avoid having this repetetive code above?
class BaseController
{
protected static IActionResult GenericAction(object request)
{
var result = Mediatr.Send(request);
if(result == null)
{
return NotFound();
}
return Ok(result);
}
}
Then
class SomeController : BaseController
{
public Action Foo(SomeRequest request)
{
return GenericAction(request);
}
}
if your methods always has same structure you can even generalize it more
class BaseController<TRequest>
{
public virtual Action Foo(SomeRequest request)
{
return GenericAction(request);
}
protected static IActionResult GenericAction(TRequest request)
{
var result = Mediatr.Send(request);
if(result == null)
{
return NotFound();
}
return Ok(result);
}
}
Then
class SomeController<SomeRequest> : BaseController
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.