I am trying to move logic that I do on all of my controllers into a class to follow the "Do Not Repeat Yourself" principle. What I am struggling with is how to elegantly return an error code.
Here are some examples of what I currently do within each controller:
public class SomethingRequest
{
public SomethingModel Something { get; set; }
public string Token { get; set; }
}
public ActionResult GetSomething(SomethingRequest request)
{
var something = request.Something;
var token = request.Token;
if (something == null)
{
return BadRequest("Something object is null. You may have sent data incorrectly");
}
if (token == null || token != "1234")
{
return Unauthorized("Token object is null");
}
}
Now what I want to do is move the last two parts of that into their own class:
public class RequestValidation
{
public void TokenCheck(string token)
{
if (token == null || token != "1234")
{
// doesn't work
return Unauthorized("Token object is null");
}
}
public void DataCheck(object someObject)
{
if (someObject == null)
{
// doesn't work
return BadRequest("Object is null. You may have sent data incorrectly");
}
}
}
And then I want to call them from SomethingController like so
RequestValidation.TokenCheck(token);
and
RequestValidation.DataCheck(something);
and then have them return the bad request or an exception.
How should I accomplish this?