How to remove the repeated code with a base controller, base service and base repository? - Part 7
This article removes repeated code with a base controller, base service and base repository that handle exceptions, common responses, logs and traces using lambda expressions.
How to remove the repeated code with a base controller, base service and base repository? - Part 7
When the application grows, we start to see the same code at the top and the bottom of every method. Each controller action has its own try and catch, its own “not found” check and its own message. Each service method writes its own log line and measures its own time. Each repository converts the database errors in its own way, or not at all. The result is that the real work of a method is hidden in the middle of the repeated code, and when a rule changes, for example how the errors are logged, we must change it in fifty places. In the previous articles, we built the screens, the services and the repositories. In this article, we are going to remove this repeated code with three base classes, a base controller, a base service and a base repository, which handle the exceptions, the common response, the logs and the traces in one place, and take the work of the derived classes as a lambda expression.
Student Management System series:
- How to structure an ASP.NET MVC application? - Part 1
- How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
- How does routing work, with custom, nested and area routes? - Part 3
- How to model the data with Entity Framework and LINQ? - Part 4
- How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
- How to build CRUD with Razor views and dependency injection? - Part 6
- How to remove the repeated code with a base controller, base service and base repository? - Part 7 (this article)
- How to build the views with layouts, partial views and HTML helpers? - Part 8
- How to use filters, model binding and validation? - Part 9
- How to add registration, login, forgot password, change password, profile and logout? - Part 10
- How to build a Web API with ASP.NET MVC 4? - Part 11
- How to test the application and keep it clean? - Part 12
TL;DR Summary
- A base class holds the common work, and the derived class gives only the specific work, as a lambda expression (
Func<T>orAction). - The base controller
Execute(() => ...)converts the expected exceptions to the right result, the 404 for not found, the message for a business rule, and the unexpected ones go to theOnException, which logs and shows the error page. - The base Web API controller wraps every result in the common response (
ApiResponse<T>) with the success flag, the data, the message, the errors and the trace id, and selects the status code from the exception. - The base service logs the start, the end and the time of every operation, and logs the expected errors as warnings and the unexpected ones as errors.
- The base repository gives the basic operations for all the entities, and translates the database exceptions to our
DataAccessException. - The domain exceptions (
NotFoundException,BusinessRuleException,ValidationFailedException,DataAccessException) are the common language between the layers. - An
ILoggerabstraction and the trace id of the request tie all the log lines of one request together.
Common Challenges
The try and catch in every action
An action with its own try and catch is mostly the catch which writes the log and returns an error. It is the same in every action, and one action always forgets it.
Different errors for the same problem
The same missing student returns the 404 page from one controller, an empty page from another and an exception from the third. The API returns the 200 with the text “error” in the body. The clients can’t depend on anything.
The logs which nobody can follow
When every layer writes the lines in its own format and without any link, one failed request is ten lines which are mixed with the lines of the other requests. Nobody can say which lines belong together.
The database errors reach the user
A DbUpdateException which is not handled shows the SQL details in the browser, which is bad for the security and useless for the user.
The design
The following diagram shows the three base classes and the classes which derive from them.

Each base class does the same kind of work for its layer, and all of them use the same ILogger. The derived classes keep only what is specific to them. Before the code, we need the common language, the exceptions, and the logger.
The common language of the layers
The layers must tell each other what went wrong, without knowing the technology of the other layer. We define four exceptions in the SMS.Domain project, which every layer can reference,
// The requested data does not exist, the web layer returns 404
public class NotFoundException : Exception
{
public NotFoundException(string entity, object key)
: base(string.Format("{0} {1} was not found", entity, key))
{
}
}
// A business rule rejects the operation, the web layer returns the message to the user (409 in the API)
public class BusinessRuleException : Exception
{
public BusinessRuleException(string message) : base(message)
{
}
}
// The data is not valid, the errors are by the field name (400)
public class ValidationFailedException : Exception
{
public ValidationFailedException(IDictionary<string, string[]> errors) : base("The data is not valid")
{
Errors = errors;
}
public IDictionary<string, string[]> Errors { get; private set; }
}
// The database failed, the details are only for the log (500)
public class DataAccessException : Exception
{
public DataAccessException(string message, Exception inner) : base(message, inner)
{
}
}
The first three are the expected problems. They have a message which is safe to show to the user. The fourth one is a technical failure, and its message must never reach the user. The StudentService.Enroll in Part 5 used the ArgumentException and the InvalidOperationException for the same problems, and now it throws the NotFoundException and the BusinessRuleException, so the controllers don’t have to guess what an exception means.
The logger is an interface in the SMS.Domain, so the services and the repositories don’t depend on any logging library,
public interface ILogger
{
void Debug(string format, params object[] args);
void Info(string format, params object[] args);
void Warn(string format, params object[] args);
void Error(Exception exception, string format, params object[] args);
}
// The short id which ties together all the log lines of one request
public static class TraceId
{
public static string Current
{
get
{
var id = Trace.CorrelationManager.ActivityId;
return id == Guid.Empty ? "-" : id.ToString("N").Substring(0, 8);
}
}
}
The TraceId reads the ActivityId of the .NET Trace.CorrelationManager, which is the standard place for the correlation id of an operation. The Application_BeginRequest of the Global.asax.cs sets a new one for each request,
protected void Application_BeginRequest()
{
Trace.CorrelationManager.ActivityId = Guid.NewGuid();
}
The implementation writes to a TraceSource, so the listeners decide where the lines go. We add a file listener at the start of the application. In 2012 the log4net and NLog are the popular choices, and either of them can implement the same ILogger without any change in the other code,
public class TraceLogger : ILogger
{
private static readonly TraceSource Source = new TraceSource("SMS", SourceLevels.All);
public static void LogToFile(string path)
{
Source.Listeners.Add(new TextWriterTraceListener(path));
}
public void Info(string format, params object[] args)
{
Write(TraceEventType.Information, "INFO ", string.Format(format, args));
}
// Debug, Warn and Error are the same, with another event type and level text
private static void Write(TraceEventType type, string level, string text)
{
var message = string.Format("{0:HH:mm:ss.fff} {1} [{2}] {3}", DateTime.Now, level, TraceId.Current, text);
Source.TraceEvent(type, 0, message);
Source.Flush();
}
}
Every line has the time, the level and the trace id in the brackets. The logger is registered as one instance in the Unity container (container.RegisterInstance<ILogger>(new TraceLogger())), and it is injected to the classes through their constructors, as all the other dependencies.
The base repository
The repositories of Part 4 and Part 6 had the same four methods, GetAll, Find, Add and Remove, copied for each entity. The generic IRepository<T> and the EfRepository<T> hold them once,
public interface IRepository<T> where T : Entity
{
IQueryable<T> GetAll();
T Find(int id);
void Add(T entity);
void Remove(T entity);
}
public interface IStudentRepository : IRepository<Student> { }
public interface IDepartmentRepository : IRepository<Department> { }
public interface ICourseRepository : IRepository<Course> { }
The specific interfaces stay, so the services still depend on the IStudentRepository, and a repository can add its own methods later. The base class is in the SMS.Data project,
public abstract class EfRepository<T> : IRepository<T> where T : Entity
{
protected EfRepository(SchoolContext context, ILogger logger)
{
Context = context;
Logger = logger;
}
protected SchoolContext Context { get; private set; }
protected ILogger Logger { get; private set; }
// The query which every read of the repository starts with, a repository adds the Include here
protected virtual IQueryable<T> Query()
{
return Context.Set<T>();
}
public virtual IQueryable<T> GetAll()
{
return Query();
}
public virtual T Find(int id)
{
return Execute("Find", () => Query().SingleOrDefault(e => e.Id == id));
}
public virtual void Add(T entity)
{
Execute("Add", () => Context.Set<T>().Add(entity));
}
public virtual void Remove(T entity)
{
Execute("Remove", () => Context.Set<T>().Remove(entity));
}
protected TResult Execute<TResult>(string operation, Func<TResult> action)
{
var name = GetType().Name + "." + operation;
var timer = Stopwatch.StartNew();
try
{
var result = action();
Logger.Debug("{0} took {1} ms", name, timer.ElapsedMilliseconds);
return result;
}
catch (DataException ex)
{
Logger.Error(ex, "{0} failed after {1} ms", name, timer.ElapsedMilliseconds);
throw new DataAccessException("The data could not be read or changed", ex);
}
}
}
The important part is the Execute. The operation is given as a lambda expression, () => Query().SingleOrDefault(...), and the base class decides how to run it, with the timer, the debug line and the translation of the Entity Framework errors (DataException is the base class of them) to our DataAccessException. The concrete repositories are now very short. They override only what is special, the Include of the related data,
public class StudentRepository : EfRepository<Student>, IStudentRepository
{
public StudentRepository(SchoolContext context, ILogger logger) : base(context, logger)
{
}
public override Student Find(int id)
{
return Execute("Find", () => Context.Students
.Include(s => s.Enrollments.Select(e => e.Course))
.SingleOrDefault(s => s.Id == id));
}
}
public class DepartmentRepository : EfRepository<Department>, IDepartmentRepository
{
public DepartmentRepository(SchoolContext context, ILogger logger) : base(context, logger)
{
}
protected override IQueryable<Department> Query()
{
return Context.Departments.Include(d => d.Courses);
}
}
The GetAll returns an IQueryable, which is not executed yet (the deferred execution of Part 4), so there is nothing to time or to catch inside it. The errors of such a query appear later, in the service which calls ToList(). It is the reason why the base service also has the same kind of Execute.
The SaveChanges is in the UnitOfWork, and the database errors of the changes are translated there,
public void Commit()
{
try
{
var changes = _context.SaveChanges();
_logger.Debug("UnitOfWork.Commit saved {0} change(s)", changes);
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors
.SelectMany(e => e.ValidationErrors)
.GroupBy(e => e.PropertyName)
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());
throw new ValidationFailedException(errors);
}
catch (DbUpdateException ex)
{
_logger.Error(ex, "UnitOfWork.Commit failed");
throw new DataAccessException("The changes could not be saved", ex);
}
}
An entity which breaks the rules of the model, for example a student without the last name, is a ValidationFailedException with the errors by the field, and the other database errors are the DataAccessException. The integration test of this behavior is,
[Test]
public void Commit_WithAnInvalidStudent_ThrowsAValidationFailedException()
{
_context.Students.Add(new Student { FirstName = "A", Email = "a@example.com", CreatedOn = DateTime.UtcNow });
var unitOfWork = new UnitOfWork(_context, new NullLogger());
var ex = Assert.Throws<ValidationFailedException>(() => unitOfWork.Commit());
Assert.IsTrue(ex.Errors.ContainsKey("LastName"));
}
The base service
The service has the same need. Every operation should log its start and its end with the time, and the failures should be logged with the right level. An expected problem, like a missing student or a rejected business rule, is a warning, because the system works as designed. An unexpected one is an error. The base service does it once,
public abstract class BaseService
{
protected BaseService(ILogger logger)
{
Logger = logger;
}
protected ILogger Logger { get; private set; }
protected T Execute<T>(string operation, Func<T> action)
{
var name = GetType().Name + "." + operation;
var timer = Stopwatch.StartNew();
Logger.Info("{0} started", name);
try
{
var result = action();
Logger.Info("{0} finished in {1} ms", name, timer.ElapsedMilliseconds);
return result;
}
catch (Exception ex)
{
if (ex is NotFoundException || ex is BusinessRuleException || ex is ValidationFailedException)
Logger.Warn("{0} stopped: {1}", name, ex.Message);
else
Logger.Error(ex, "{0} failed after {1} ms", name, timer.ElapsedMilliseconds);
throw;
}
}
protected void Execute(string operation, Action action)
{
Execute<object>(operation, () =>
{
action();
return null;
});
}
}
There are two overloads, one for the operation which returns a value (Func<T>) and one for the operation which doesn’t (Action). The second one calls the first, so the logic is written once. The exception is always thrown again with throw;, which keeps the original stack trace. The base service only logs, it doesn’t decide what to show to the user, that is the job of the web layer. Now the StudentService has the work only,
public class StudentService : BaseService, IStudentService
{
private readonly IStudentRepository _students;
private readonly IUnitOfWork _unitOfWork;
public StudentService(IStudentRepository students, IUnitOfWork unitOfWork, ILogger logger)
: base(logger)
{
_students = students;
_unitOfWork = unitOfWork;
}
public int Create(Student student)
{
return Execute("Create", () =>
{
if (_students.GetAll().Any(s => s.Email == student.Email))
throw new BusinessRuleException("A student with the email " + student.Email + " already exists");
student.CreatedOn = DateTime.UtcNow;
_students.Add(student);
_unitOfWork.Commit();
return student.Id;
});
}
public Student Find(int id)
{
return Execute("Find", () => _students.Find(id));
}
public int Count()
{
return Execute("Count", () => _students.GetAll().Count());
}
public void Enroll(int studentId, int courseId)
{
Execute("Enroll", () =>
{
var student = _students.Find(studentId);
if (student == null)
throw new NotFoundException("Student", studentId);
if (student.Enrollments.Any(e => e.CourseId == courseId))
throw new BusinessRuleException("The student is already enrolled in this course");
student.Enrollments.Add(new Enrollment { CourseId = courseId, CreatedOn = DateTime.UtcNow });
_unitOfWork.Commit();
});
OnStudentEnrolled(new StudentEnrolledEventArgs { StudentId = studentId, CourseId = courseId });
}
// Search, BornIn, Update and Delete use the same Execute
}
The Create method has a new business rule, the email of a student must be unique, and the rule is written as the throw of the BusinessRuleException. There is no log line, no try and catch and no timer in the method. The event is raised after the Execute, only when the enrollment really succeeded. The unit tests can read the log through a fake logger, which is a list of the lines,
[Test]
public void Execute_LogsTheStartAndTheEndOfAnOperation()
{
_service.Count();
Assert.IsTrue(_logger.Lines.Any(l => l.StartsWith("INFO StudentService.Count started")));
Assert.IsTrue(_logger.Lines.Any(l => l.StartsWith("INFO StudentService.Count finished")));
}
[Test]
public void Enroll_ForAMissingStudent_IsLoggedAsAWarningAndNotAsAnError()
{
Assert.Throws<NotFoundException>(() => _service.Enroll(99, 1));
Assert.AreEqual(0, _logger.Errors);
Assert.IsTrue(_logger.Lines.Any(l => l.StartsWith("WARN StudentService.Enroll stopped")));
}
The base controller
The base controller has three jobs. It converts the expected exceptions to the right result, it logs the start of every action, and it is the last safety net for the unexpected errors. The first job is the Execute, which takes the body of the action as a lambda expression returning an ActionResult, and an optional second lambda for the business errors,
public abstract class BaseController : Controller
{
protected BaseController(ILogger logger)
{
Logger = logger;
}
protected ILogger Logger { get; private set; }
protected ActionResult Execute(Func<ActionResult> action, Func<Exception, ActionResult> onRuleError = null)
{
try
{
return action();
}
catch (NotFoundException ex)
{
Logger.Warn("{0} returns 404: {1}", GetType().Name, ex.Message);
return HttpNotFound(ex.Message);
}
catch (ValidationFailedException ex)
{
foreach (var error in ex.Errors)
foreach (var message in error.Value)
ModelState.AddModelError(error.Key, message);
return RuleError(ex, onRuleError);
}
catch (BusinessRuleException ex)
{
return RuleError(ex, onRuleError);
}
}
protected ActionResult Success(string message, ActionResult next)
{
TempData["Message"] = message;
return next;
}
private ActionResult RuleError(Exception ex, Func<Exception, ActionResult> onRuleError)
{
Logger.Warn("{0} rejected the request: {1}", GetType().Name, ex.Message);
if (onRuleError != null)
return onRuleError(ex);
TempData["Error"] = ex.Message;
return RedirectToAction("Index");
}
// OnActionExecuting and OnException are shown below
}
The Success is a small helper for the Post-Redirect-Get of Part 6, it sets the message for the next request and returns the redirect. The StudentsController now derives from the BaseController, and its actions look like this,
public ActionResult Details(int id)
{
return Execute(() => View(BuildDetailsModel(FindStudent(id))));
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentFormModel model)
{
return Execute(() =>
{
if (!ModelState.IsValid)
return View(model);
_service.Create(new Student
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
DateOfBirth = model.DateOfBirth,
IsActive = true
});
return Success("Student created", RedirectToAction("Index"));
},
ex =>
{
ModelState.AddModelError(string.Empty, ex.Message);
return View(model);
});
}
// One place for the "not found" rule of all the actions
private Student FindStudent(int id)
{
var student = _service.Find(id);
if (student == null)
throw new NotFoundException("Student", id);
return student;
}
The first lambda is the happy path, and the second lambda is what to do when a business rule rejects the request. For the create screen it puts the message in the form, so the user can correct the email and post again. The repeated if (student == null) return HttpNotFound(); of the earlier articles is now the one private method FindStudent, and the base controller turns its exception to the 404. The Enroll uses the second lambda to go back to the details page with the message,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Enroll(int id, int? courseId)
{
return Execute(() =>
{
if (!courseId.HasValue)
throw new BusinessRuleException("Select a course to enroll");
_service.Enroll(id, courseId.Value);
return Success("Student enrolled in the course", RedirectToAction("Details", new { id = id }));
},
ex =>
{
TempData["Error"] = ex.Message;
return RedirectToAction("Details", new { id = id });
});
}
Here is the screen when a user tries to create a student with an email which exists already. The rule is in the service, the controller only shows the message,

The safety net for the unexpected errors
The Execute doesn’t catch the Exception. A programming error or a database failure is not something to show in the form, it should be logged and shown as a clear error page. The base controller overrides the OnException, which the MVC calls (as an exception filter, Part 9) for every unhandled exception of the action. The same class logs the start of each action with the OnActionExecuting,
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
Logger.Info("{0}.{1} started", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
base.OnActionExecuting(filterContext);
}
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
Logger.Error(filterContext.Exception, "Unhandled error in {0}", GetType().Name);
filterContext.ExceptionHandled = true;
if (filterContext.HttpContext != null && filterContext.HttpContext.Response != null)
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
filterContext.Result = View("Error", new ErrorViewModel
{
Message = "Something went wrong. The error is written in the log.",
TraceId = TraceId.Current
});
}
The user gets the status 500 and the Error view, which shows only a friendly message and the trace id. The exception type, the message and the stack are not shown. The Error.cshtml view of Views/Shared is,
@model ErrorViewModel
@{
ViewBag.Title = "Error";
}
<h2>Sorry, there is a problem</h2>
<p class="error">@Model.Message</p>
<p>If you contact the support, give this trace id: <code>@Model.TraceId</code></p>
To see it, the Admin dashboard of the sample has a link “Raise a test error”, which calls an action that throws an InvalidOperationException on purpose,

A support person can search the trace id in the log file, and see everything which happened in that request. The following is the real trace file of the sample, for some requests. The first request is a missing student (the 404), the second is a successful create and the third is a rejected create with the same email, and the last one is the test error. Look at the trace id in the brackets, which tie the lines of each request,
21:44:48.663 INFO [1245351e] StudentService.Find started
21:44:48.667 DEBUG [1245351e] StudentRepository.Find took 1 ms
21:44:48.667 INFO [1245351e] StudentService.Find finished in 2 ms
21:44:48.667 WARN [1245351e] StudentsController returns 404: Student 999 was not found
21:44:48.917 INFO [4f1f08c9] StudentService.Create started
21:44:48.945 DEBUG [4f1f08c9] StudentRepository.Add took 7 ms
21:44:49.040 DEBUG [4f1f08c9] UnitOfWork.Commit saved 1 change(s)
21:44:49.040 INFO [4f1f08c9] StudentService.Create finished in 124 ms
21:44:49.280 INFO [54773792] StudentService.Create started
21:44:49.280 WARN [54773792] StudentService.Create stopped: A student with the email aarav.bose@example.com already exists
21:44:49.280 WARN [54773792] StudentsController returns 409: A student with the email aarav.bose@example.com already exists
21:44:50.281 INFO [778a5767] Dashboard.Fail started
21:44:50.282 ERROR [778a5767] Unhandled error in DashboardController | InvalidOperationException: This error is raised on purpose
Note the levels. The missing student and the rejected email are warnings, they are the expected problems and the system worked as designed. Only the real failure is an error, so a monitoring tool which watches for the ERROR lines doesn’t wake somebody up for a wrong email. The line “StudentsController returns 409” in the third request is written by the Web API controller of the next section, because the sample trace was taken from the API requests, and the MVC controller writes the same kind of line with its own class name.
The base Web API controller and the common response
A client of the API needs the same predictability. Every response should have the same shape, and the status code should tell what happened. The ApiResponse<T> is the envelope of all the responses,
public class ApiResponse<T>
{
public bool Success { get; set; }
public T Data { get; set; }
public string Message { get; set; }
public IDictionary<string, string[]> Errors { get; set; }
public string TraceId { get; set; }
public static ApiResponse<T> Ok(T data, string traceId)
{
return new ApiResponse<T> { Success = true, Data = data, TraceId = traceId };
}
public static ApiResponse<T> Fail(string message, IDictionary<string, string[]> errors, string traceId)
{
return new ApiResponse<T> { Success = false, Message = message, Errors = errors, TraceId = traceId };
}
}
The BaseApiController has the Execute methods, which take the action as a lambda, wrap its result in the envelope and select the status code from the exception,
public abstract class BaseApiController : ApiController
{
protected BaseApiController(ILogger logger)
{
Logger = logger;
}
protected ILogger Logger { get; private set; }
// The data of the action is wrapped in the common response
protected HttpResponseMessage Execute<T>(Func<T> action, HttpStatusCode success = HttpStatusCode.OK, Func<T, Uri> location = null)
{
return Run(() =>
{
var data = action();
var response = Request.CreateResponse(success, ApiResponse<T>.Ok(data, TraceId.Current));
if (location != null)
response.Headers.Location = location(data);
return response;
});
}
// An action without a result, like the delete
protected HttpResponseMessage Execute(Action action, HttpStatusCode success = HttpStatusCode.NoContent)
{
return Run(() =>
{
action();
return Request.CreateResponse(success);
});
}
private HttpResponseMessage Run(Func<HttpResponseMessage> action)
{
try
{
return action();
}
catch (NotFoundException ex)
{
Logger.Warn("{0} returns 404: {1}", GetType().Name, ex.Message);
return Fail(HttpStatusCode.NotFound, ex.Message, null);
}
catch (ValidationFailedException ex)
{
return Fail(HttpStatusCode.BadRequest, ex.Message, ex.Errors);
}
catch (BusinessRuleException ex)
{
Logger.Warn("{0} returns 409: {1}", GetType().Name, ex.Message);
return Fail(HttpStatusCode.Conflict, ex.Message, null);
}
catch (Exception ex)
{
Logger.Error(ex, "Unhandled error in {0}", GetType().Name);
return Fail(HttpStatusCode.InternalServerError, "An unexpected error occurred. Give the trace id to the support", null);
}
}
// InvalidModel() and Fail() build the 400 and the error responses with the same envelope
}
The mapping of the exceptions is the table which every client can rely on,
| Exception | Status code | What the client gets |
|---|---|---|
NotFoundException | 404 Not Found | The message |
ValidationFailedException and the invalid ModelState | 400 Bad Request | The message and the errors by the field |
BusinessRuleException | 409 Conflict | The message of the rule |
| Any other exception | 500 Internal Server Error | A generic message and the trace id, the details only in the log |
The location parameter of the first Execute is also a lambda. A POST which creates a resource gives the way to build its Location header from the created data, and the base class sets it. With the base class, the Web API controller of Part 11 becomes,
public class StudentsController : BaseApiController
{
private readonly IStudentService _service;
public StudentsController(IStudentService service, ILogger logger) : base(logger)
{
_service = service;
}
// GET api/students/5
public HttpResponseMessage Get(int id)
{
return Execute(() => StudentDto.From(FindStudent(id)));
}
// POST api/students
public HttpResponseMessage Post(StudentInputDto model)
{
if (model == null || !ModelState.IsValid)
return InvalidModel();
var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Path).TrimEnd('/');
return Execute(() =>
{
var student = new Student
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
DateOfBirth = model.DateOfBirth,
IsActive = true
};
_service.Create(student);
return StudentDto.From(student);
},
HttpStatusCode.Created,
dto => new Uri(baseUrl + "/" + dto.Id));
}
// DELETE api/students/5
public HttpResponseMessage Delete(int id)
{
return Execute(() =>
{
FindStudent(id);
_service.Delete(id);
});
}
}
Find below the real responses of these actions. A student, a missing student, a created student, a duplicate email, and an invalid request. All of them have the same envelope, with the TraceId which can be searched in the log,
GET /api/students/1
HTTP/1.1 200 OK
{"Success":true,"Data":{"Id":1,"FirstName":"Anand","LastName":"Kumar","FullName":"Anand Kumar",
"Email":"anand.kumar@example.com","DateOfBirth":"1990-01-01T00:00:00","IsActive":true},
"Message":null,"Errors":null,"TraceId":"b170aeca"}
GET /api/students/999
HTTP/1.1 404 Not Found
{"Success":false,"Data":null,"Message":"Student 999 was not found","Errors":null,"TraceId":"1245351e"}
POST /api/students (a new student)
HTTP/1.1 201 Created
Location: http://localhost:8099/api/students/21
{"Success":true,"Data":{"Id":21,"FirstName":"Aarav","LastName":"Bose", ... },"Message":null,"Errors":null,"TraceId":"4f1f08c9"}
POST /api/students (the same email again)
HTTP/1.1 409 Conflict
{"Success":false,"Data":null,"Message":"A student with the email aarav.bose@example.com already exists",
"Errors":null,"TraceId":"54773792"}
POST /api/students (an invalid body)
HTTP/1.1 400 Bad Request
{"Success":false,"Data":null,"Message":"The request is invalid","Errors":{
"model.FirstName":["The FirstName field is required."],
"model.Email":["The Email field is not a valid e-mail address."],
"model.DateOfBirth":["The student must be at least 16 years old"]},"TraceId":"aa2b5447"}
The jQuery of the Quick search screen reads the list from the Data property of the envelope (response.Data). The unit tests prove the status codes, including the most important one, that the details of an unexpected failure are logged and are not sent to the client,
[Test]
public void Post_WhenTheServiceFails_ReturnsServerErrorAndLogsIt()
{
var logger = new FakeLogger();
var service = new FakeStudentService { CreateException = new InvalidOperationException("secret detail") };
var controller = CreateController(service, logger);
var response = controller.Post(new StudentInputDto { FirstName = "A", LastName = "Kumar", Email = "a@example.com", DateOfBirth = new DateTime(1990, 1, 1) });
Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.AreEqual(1, logger.Errors);
Assert.IsFalse(response.Content.ReadAsStringAsync().Result.Contains("secret detail"));
}
The same for the MVC base controller, the OnException is tested through the IExceptionFilter interface,
[Test]
public void AnUnexpectedException_IsLoggedAndShowsTheErrorView()
{
var logger = new FakeLogger();
var controller = new StudentsController(new FakeStudentService(), new FakeCatalogService(), logger);
var context = new ExceptionContext { Exception = new InvalidOperationException("boom"), HttpContext = new FakeHttpContext("~/") };
((IExceptionFilter)controller).OnException(context);
var view = context.Result as ViewResult;
Assert.IsTrue(context.ExceptionHandled);
Assert.IsNotNull(view);
Assert.AreEqual("Error", view.ViewName);
Assert.AreEqual(500, context.HttpContext.Response.StatusCode);
Assert.AreEqual(1, logger.Errors);
}
When to use a base class
The three base classes remove a lot of repeated code, but a base class is also the strongest coupling between two classes (Part 1 of the Maintainable Code series). Find below the points to keep in mind,
- Keep the base class small and about one concern. Ours do the error handling, the logging and the basic data operations, nothing about the business.
- The base class calls the derived class through a lambda or a virtual method, never the other way around. The derived classes don’t depend on how the base works, only on its contract.
- Use the template method for the variation. The
Query()of the repository is a virtual method which the derived repository overrides, and the baseFindandGetAlluse it. It is the Open Closed Principle with the inheritance. - Don’t put a rule in the base class which is not true for all the derived classes. If a controller must not log, it can’t derive from our
BaseController, which is a sign of the Liskov Substitution problem. - The decision of the status code and the page is in the web layer only. The service layer throws the domain exceptions and doesn’t know the HTTP.
- The base classes don’t replace the global filters. The
ActionTimerfilter of Part 9 is a global filter because it has nothing to do with the controller code, and the base controller is for the things which need the controller members, like theTempDataand theModelState.
Must Be Aware: The
Executeof the base service logs an exception and throws it again, and the base controller logs it again as a warning or an error. The same problem is in the log twice, with different class names. It is intentional here, the trace id ties the lines together, and each layer tells what it knows. In a real project decide one place for the error level (the layer which handles the exception), and keep the other layers at the warning level or lower.
Wrap up
In this article, we have looked at how the three base classes, the base controller, the base service and the base repository, hold the common work, with the work of the derived class given as a lambda expression. We have seen the domain exceptions as the common language of the layers, the ILogger and the trace id, the common response of the API, the status code mapping, the safety net of the OnException and the real trace file. I really appreciate that you took the time to read this article. In the next article, I will walk you through the views, with the layouts, the partial views and the HTML helpers.
Related Posts
How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
This article follows one ASP.NET MVC request from routing to the Razor view, and explains what changes between .NET 4.0 and 4.5, mainly the async actions.
How to build a Web API with ASP.NET MVC 4? - Part 11
This article builds an ASP.NET Web API for students on the same service, with routing, status codes, content negotiation, validation, dependency injection and a jQuery client.
How to build CRUD with Razor views and dependency injection? - Part 6
This article builds the student list, create, edit, details and delete screens with a service layer, view models, validation, Post-Redirect-Get and dependency injection with Unity.