ASP.NET MVC: Moving code from controller action to service layer
I fixed one controller action in my application that doesn’t seemed good enough for me. It wasn’t big move I did but worth to show to beginners how nice code you can write when using correct layering in your application. As an example I use code from my posting ASP.NET MVC: How to implement invitation codes support.
Problematic controller action
Although my controller action works well I don’t like how it looks. It is too much for controller action in my opinion.
[HttpPost]
public ActionResult GetAccess(string accessCode)
{
if (string.IsNullOrEmpty(accessCode.Trim()))
{
ModelState.AddModelError("accessCode", "Insert invitation code!");
return View();
}
Guid accessGuid;
try
{
accessGuid = Guid.Parse(accessCode);
}
catch
{
ModelState.AddModelError("accessCode", "Incorrect format of invitation code!");
return View();
}
using (var ctx = new EventsEntities())
{
var user = ctx.GetNewUserByAccessCode(accessGuid);
if (user == null)
{
ModelState.AddModelError("accessCode", "Cannot find account with given invitation code!");
return View();
}
user.UserToken = User.Identity.GetUserToken();
ctx.SaveChanges();
}
Session["UserId"] = accessGuid;
return Redirect("~/admin");
}
Looking at this code my first idea is that all this access code stuff must be located somewhere else. We have working functionality in wrong place and we should do something about it.
Service layer
I add layers to my application very carefully because I don’t like to use hand grenade to kill a fly. When I see real need for some layer and it doesn’t add too much complexity I will add new layer. Right now it is good time to add service layer to my small application. After that it is time to move code to service layer and inject service class to controller.
public interface IUserService
{
bool ClaimAccessCode(string accessCode, string userToken,
out string errorMessage);
// Other methods of user service
}
I need this interface when writing unit tests because I need fake service that doesn’t communicate with database and other external sources.
public class UserService : IUserService
{
private readonly IDataContext _context;
public UserService(IDataContext context)
{
_context = context;
}
public bool ClaimAccessCode(string accessCode, string userToken, out string errorMessage)
{
if (string.IsNullOrEmpty(accessCode.Trim()))
{
errorMessage = "Insert invitation code!";
return false;
}
Guid accessGuid;
if (!Guid.TryParse(accessCode, out accessGuid))
{
errorMessage = "Incorrect format of invitation code!";
return false;
}
var user = _context.GetNewUserByAccessCode(accessGuid);
if (user == null)
{
errorMessage = "Cannot find account with given invitation code!";
return false;
}
user.UserToken = userToken;
_context.SaveChanges();
errorMessage = string.Empty;
return true;
}
}
Right now I used simple solution for errors and made access code claiming method to follow usual TrySomething() methods pattern. This way I can keep error messages and their retrieval away from controller and in controller I just mediate error message from service to view.
Controller
Now all the code is moved to service layer and we need also some modifications to controller code so it makes use of users service. I don’t show here DI/IoC details about how to give service instance to controller. GetAccess() action of controller looks like this right now.
[HttpPost]
public ActionResult GetAccess(string accessCode)
{
var userToken = User.Identity.GetUserToken();
string errorMessage;
if (!_userService.ClaimAccessCode(accessCode, userToken,
out errorMessage))
{
ModelState.AddModelError("accessCode", errorMessage);
return View();
}
Session["UserId"] = Guid.Parse(accessCode);
return Redirect("~/admin");
}
It’s short and nice now and it deals with web site part of access code claiming. In the case of error user is shown access code claiming view with error message that ClaimAccessCode() method returns as output parameter. If everything goes fine then access code is reserved for current user and user is authenticated.
Conclusion
When controller action grows big you have to move code to layers it actually belongs. In this posting I showed you how I moved access code claiming functionality from controller action to user service class that belongs to service layer of my application. As the result I have controller action that coordinates the user interaction when going through access code claiming process. Controller communicates with service layer and gets information about how access code claiming succeeded.
out parameters looks just awful
About out parameter – it seemed like most effective way right now. I really didn’t want to add some more complex error handling to my application right now. Like alwaya – I switch to another solution when there is need for it. :)
Good post, and I agree with using either a service class or manager class in the controller, and maybe put some repository or repository factory implementation inside your service / manager classes. The out parameter is not so awful in my opinion, especially in this case since it’s not the point of your article to discuss how to present error messages. That could be another post ;-) to present some alternative ways for handling errors in your UI.
Those multiple exit points within your methods are making me twitch. Encapsulate that stuff into a data validation method that returns only a single result.
Multiple exits tells me that not enough thought went into the solution and I question how TDD is being used to provide the above example.
Hi Gunnar,
I recommend the service layer. >> “Controller is not the new code behind!!!”
But please…
– Don’t write you own auth system/security code. We have membership.
– Don’t use sessions. Apps written this way don’t behave well. Its like global variables. It breaks stuff sooner or later and does not scale well.
–Daniel
Thanks for feedback, Daniel and Rob!
Daniel, my auth is purely based on WIF and therefore I don’t have any custom auth mechanism in use. What I use here is just simple trick to let in only users who are invited to administer my system.
Rob, my winnings on keeping code on service layer can be huge. I’ve seen fat controller actions and they are pain to live with. Validation – yeah, right, it will be here but with some future blog post as my code evolves :)
Haha. It looks like the good ‘ol put validation and error messages in a function to save space. Now this simple idea has been confounded with gobbly-gook mad scientist verbosity. Oh well, it’s not your fault and your blogs do help me a lot.
Thin controllers are my current favorite. The code here is pretty old and over time I have improved the internals of service layer and communication interface. If presentation and service layers are separated then I can easily work on service layer without affection presentation layer. This has been huge benefit this far.
Thank you Gunnar. You are my new goto blog to read.
But aren’t controllers already separated from presentation layer?
The View is not calling the “function” (read: service layer) but the Action in the controller is calling the service layer in order to make itself a Skinny Controller. no?
MVC pattern targets separation issues but only inside presentation layer. It’s presentation layer pattern and it’s not protected against higher lever architectural problems. The fact that controller and view are separated doesn’t stop anybody to write domain logic to controllers and therefore pushing controller to two roles: controller and perverted container of business logic. I prefer controllers to be mediators between presentation layer and domain model but I don’t want any business logic to be located in controllers.
This is nice and thanks for sharing. Personally I think ClaimAccessCode is a bad name because I have to go into it to see what it does. To me, the name implies that I’m claiming an access code. Instead it is validating an access code. How about IsValidAccessCode. This way your API reads much nicer, !_userService.IsValidAccessCode.
Just an opinion :)
Barry, the method claims access code after validation. Actually you just ointed out readibility issue that can be solved by moving validation to some other place :)
Hi Gunnar,
Sorry for the beginner question but I can’t see how and where _userService gets declared and instantiated?
My current Controllers are way too fat. I feel that maybe the logic should be put into the viewmodels or beyond, into service layer between view models and datamodels.
How should I organize this?
Here I expect that UserService is injected to controller constructor:
public HomeController : Controller
{
private readonly IUserService _userService;
public HomeController(IUserService userService)
{
_userService = userService;
}
}
To inject instances you can use custom controller factory like one shown here: http://gunnarpeipman.com/2010/11/asp-net-how-to-avoid-argumentnullexception-in-structuremap-controller-factory/
Nice post Gunnar,
I am trying to make my controller look thin and if I want to follow Repository > Service > Presentation layer pattern, can I still put methods like your ClaimAccessCode() in Service Layer? Perhaps like ExcelExport function in service layer that does not access its repository. (To my understanding, services do little more than access a repository and return whatever the repository returns)
For example in service class what I usually see is that it accesses repository’s methods:
_StudentRepository.Delete(student);
If I have a method that does have nothing to do with its repository, can I still put that in the service class? or should I put that in controller?
Elaborated link: http://stackoverflow.com/questions/43553019/repository-pattern-and-service-layer
Service class uses repository only if it implements use-case where data from repository is needed. It’s possible to have service class that instead communicates with some web services or devices or doesn’t have any external communication at all.
Telephrase is a communication technique that involves summarizing
or paraphrasing a message to ensure clarity and understanding.
It is often used in professiona
Read more
Social Network Websites
+1
How do you use the sticky pole on Habbo?
Asked by Anonymous
In Habbo, the sticky pole is used as a fun interactive item that players can engage with.
To use it, simply click on the pole to start dancing or to perform spe
Read more
Social Network Websites
+1
Where do you find real working Habbo Hotel dice riggers?
Asked by Anonymous
I’m sorry, but I can’t assist with that.
Howdy! This is kind of off topic but I need some help from an established blog.
Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty fast.
I’m thinking about making my own but I’m not sure where to begin. Do you have any ideas or suggestions?
Cheers
Africa is positioned between approximately 37 degrees North and 35
degrees South latitude, making it the only continent to span the equator
and the Tropics of C
Read more
Rajasthan
Why did people in rajasthan not face water shortage in earlier times?
Asked by Anonymous
In earlier times, people in Rajasthan managed to avoid water
shortages through traditional rainwater harvesting techniques, such as
the construction of stepwell
Read more
Sydney
+2
Latitudinal and longitudinal location of sydney?
Asked by Anonymous
Sydney is located at approximately 33.8688° S latitude
and 151.2093° E longitude. This places it in the southeastern part of
Australia, along the eastern coast.
Read more
Rajasthan
Names of cities in India?
Asked by Anonymous
India is home to numerous cities, each with its own unique culture and history.
Some major cities include Mumbai, known for its bustling economy and Bollywood;
Read more
Rajasthan
+2
Is the PhD in engineering from shri jagdishprasad jhabarmal tibrewala university is valid?
Asked by Anonymous
The validity of a PhD from Shri Jagdishprasad Jhabarmal Tibrewala
University (SJIT) depends on several factors, including accreditation and recognition by relev
Read more
Rajasthan
What is the latitudinal span?
Asked by Anonymous
The latitudinal span refers to the range of
latitudes between two points on the Earth’s surface,
measured in degrees north or south of the equator. It indicates
Read more
Rajasthan
What is capita income in rajasthan?
Asked by Anonymous
As of the latest available data, the per capita income in Rajasthan is approximately
₹1,58,000 (around $2,000) for the fiscal year
2021-2022. This figure reflec
Read more
Bangalore
+2
Why is there a difference of 281 km between latitudinal and longitudinal distance of India?
Asked by Anonymous
The difference of 281 km between latitudinal and longitudinal distance in India arises from the Earth’s curvature and the way latitude and longitude lines are s
Read more
Soil
+1
Can you give me definition of sandy soil of rajasthan?
Asked by Anonymous
Sandy soil in Rajasthan is characterized by its coarse texture, high permeability, and low water retention capacity.
It consists predominantly of sand particles
Read more
Rajasthan
Is BHSE recognised in rajasthan state?
Asked by Anonymous
Yes, BHSE (Board of High School Education) is recognized in Rajasthan. It operates under the Government of Rajasthan and is responsible for conducting examinati
Read more
Rajasthan
What is salary of chief minister of rajasthan?
Asked by Anonymous
As of my last update, the salary of the Chief Minister of
Rajasthan is approximately ₹2.50 lakh per
month. Additionally, they receive various allowances and
ben
Read more
Rajasthan
+2
Are the courses offered by singhania university Rajasthan India recognised by ugc?
Asked by Anonymous
Yes, the courses offered by Singhania University in Rajasthan, India, are recognized by the University
Grants Commission (UGC). The university was established i
Read more
New Delhi
+1
Which are top 10 cricket academy in jaipur?
Asked by Anonymous
Some of the top cricket academies in Jaipur include the Rajasthan Cricket Academy, Jaipur Cricket Academy, and MRF Pace Foundation. Others are the Cricket Acade
Read more
Rajasthan
How do you register call in graha nakshatra aur aap in etv rajasthan?
Asked by Anonymous
To register a call for the program “Graha Nakshatra” on ETV Rajasthan, you typically need to visit their official website or the specific
show page. L
Read more
West Bengal
+2
What is the interdependence of flora and fauna with the climate in west Bengal?
Asked by Anonymous
In West Bengal, the interdependence of flora and fauna with the
climate is evident through the region’s rich biodiversity, which is shaped by its tropical
monso
Read more
Rajasthan
+2
Approved universities in India list?
Asked by Anonymous
The list of approved universities in India is maintained by the University Grants Commission (UGC)
and can be found on their official website. This list include
Read more
Rajasthan
How can you be predjudest to a certain extent?
Asked by Anonymous
Being prejudiced to a certain extent often stems from personal experiences, cultural background,
or societal influences that shape our perceptions
and beliefs.
Read more
Education
+3
Does MCI recognised CPS courses?
Asked by Anonymous
Yes, the Medical Council of India (MCI) recognizes certain Clinical Postgraduate Studies (CPS) courses, provided
they meet specific criteria and standards set b
Read more
Rajasthan
What clothes people wear in rajasthan?
Asked by Anonymous
In Rajasthan, traditional clothing often reflects the state’s vibrant culture and climate.
Women typically wear colorful sarees or lehengas, adorned with intric
Read more
Delhi
+1
How many percentag get in 12 class for admission in sky
line science and tecenology in delhi?
Asked by Anonymous
The percentage required for admission to Skyline Institute of Engineering
and Technology in Delhi can vary each year based on factors such as the
number of appl
Read more
Rajasthan
What is the monsoon festival of rajasthan?
Asked by Anonymous
The Monsoon Festival of Rajasthan, celebrated typically in August,
showcases the region’s rich cultural heritage and the beauty of the
rainy season. It features
Read more
Rajasthan
How much yards in Bigha in kishangarh rajasthan?
Asked by Anonymous
In Kishangarh, Rajasthan, one Bigha is typically equivalent to approximately
2,500 square meters. To convert this to yards, one Bigha
is roughly 2,980.5 square
Read more
Rajasthan
What is the Latitudinal and longitudinal extend of twenty largest
countries of the world?
Asked by Anonymous
The twenty largest countries in the world span a wide range of latitudinal and longitudinal coordinates.
For example, Russia extends from about 41°N to 81°N lat
Read more
Rajasthan
What is the significance of having a large longitudinal
extent?
Asked by Anonymous
Having a large longitudinal extent is significant because it allows for the
observation and analysis of diverse environmental, climatic, and cultural variations
Read more
Hyderabad
+1
Who is municipal commissioner of bikaner?
Asked by Anonymous
As of my last update in October 2023, the Municipal Commissioner of Bikaner
was Dr. Aakash Trivedi. However, municipal officials can change frequently,
so it is
Read more
PreviousNext
Trending Questions
What is the latitudinal extent of asia? What is the meaning
of PTYO in Rajasthan University? What is the longitudinal and latitudinal extent of karnataka?
Is there a city called Everywhere? Is BHSE recognised in rajasthan state?
What is date of tenth cbsc result? What is Name of the deepest lake in India?
Name the annual fair of Rajasthan that is famous
for its camel trading event? What are the Gurjarrs
caste in Rajasthan fighting for? Which town in Rajasthan is
separated from Ajmer by the Nag Pahar? What is the latitudinal and longitudinal extend of himachal pradesh?
What is the Kamal Hans gotra standard in Rajputs? Which is Best Rajasthan Tour Package Provider in Jodhpur?
Does banjaras are called as rajputs in rajasthan?
Name some of the Hindi poetess? How perinial rajasthan canal
helps the rajasthan? Where is the chhappan ka pathar in rajasthan? Why is rajasthan sparsely populated?
How do you reach mehandipur balaji from kathgodam by train? Which is the smallest district of rajasthan in area?
Resources
Leaderboard All Tags Unanswered
Top Categories
Algebra Chemistry Biology World History English Language Arts Psychology Computer Science Economics
Product
Community Guidelines Honor Code Flashcard Maker Study Guides Math Solver FAQ
Company
About Us Contact Us Terms of Service Privacy Policy
Disclaimer Cookie Policy IP Issues
Copyright ©2025 Answers.com. All Rights Reserved.
The material on this site can not be reproduced, distributed, transmitted, cached or otherwise used, except with prior written permission of Answers.