I'm trying to reuse a method which I've to use in multiple controller class.
What I've tried is to make a static method and use in my controller class which throws argument exceptions.
Is there any way where I can use static methods directly returning BadRequest() and NotFound() and other API's Status.
public class Resuable : ControllerBase
{
private readonly ServerContext _context;
private readonly ServerViewContext _viewcontext;
private readonly AppDbContext _appdbcontext;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly JwtService _jwtService;
private readonly IFileService _fileService;
public Resuable(ServerViewContext viewcontext, ServerContext context, AppDbContext appDbContext, IWebHostEnvironment webHostEnvironment, JwtService jwtService, IFileService fileService)
{
_context = context;
_viewcontext = viewcontext;
_appdbcontext = appDbContext;
_webHostEnvironment = webHostEnvironment;
_jwtService = jwtService;
_fileService = fileService;
}
public static async Task<ActionResult<CustomerDetails>> GetCustomer(ServerContext _context, string Ph)
{
if (Ph.Length < 5 || Ph == null)
{
throw new ArgumentException("Please enter atleast 5 digit Phone number");
}
var cust = _context.TDataHeaders.FirstOrDefault(x => x.Phone == Ph);
if (cust == null)
{
throw new ArgumentException("Phone number " + Ph + " not found in our database!");
}
else
{
var dto = new CustomerDetails
{
id = cust.HeaderId,
CustomerName = cust.CustomerName,
Phone = cust.Phone,
Address = cust.Address,
Country = cust.Country,
ShipTo = cust.ShipTo,
Source = cust.Source,
};
return dto;
}
}
}
What I've tried is using methods without static and use in the same controller class like this and works perfectly fine, but the problem is I've to copy and paste in my each controller class.
[NonAction]
public ActionResult<CustomerDetails> GetCustomer(string Ph)
{
if (Ph.Length < 5 || Ph == null)
{
return BadRequest(new
{
message = "Please enter atleast 5 digit Phone number"
});
}
var cust = _context.TDataHeaders.FirstOrDefault(x => x.Phone == Ph);
if (cust == null)
{
return NotFound(new
{
message = "Phone number "+Ph+" not found in our database!"
});
}
else
{
var dto = new CustomerDetails
{
id = cust.HeaderId,
CustomerName = cust.CustomerName,
Phone = cust.Phone,
Address = cust.Address,
Country = cust.Country,
ShipTo = cust.ShipTo,
Source = cust.Source,
};
return dto;
}
}