BACKGROUND
I am working on a .Net Core API to drive a lyrics application. Users can sign up, submit artists & lyrics, and earn kudos / XP points in the process. Basically a community-driven lyrics website.
CODE
I have the following ArtistsController.
[Route("api/artists")]
public class ArtistsController : Controller
{
private readonly IArtistsService _artistsService;
private readonly UserManager<BbUser> _userManager;
public ArtistsController(IArtistsService artistsService, UserManager<BbUser> userManager)
{
_artistsService = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
_userManager = userManager;
}
[HttpGet]
public async Task<IActionResult> GetArtists()
{
ArtistCardDtoCollection artistCardDtoCollection;
if (User.Identity.IsAuthenticated)
{
var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByNameAsync(username);
var roles = await _userManager.GetRolesAsync(user);
artistCardDtoCollection = _artistsService.GetAllArtists(user.Id, roles.Contains("Admin"));
}
else
{
artistCardDtoCollection = _artistsService.GetAllArtists("", false);
}
return Ok( new { artists = artistCardDtoCollection });
}
[HttpGet("{slug}")]
[HttpGet("{slug}/lyrics", Name = "GetArtist")]
public async Task<IActionResult> GetArtist(string slug)
{
if (!_artistsService.ArtistExists(slug)) return NotFound();
ArtistOverviewDto artistOverviewDto;
if (User.Identity.IsAuthenticated)
{
var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByNameAsync(username);
var roles = await _userManager.GetRolesAsync(user);
artistOverviewDto = _artistsService.GetArtistBySlug(slug, user.Id, roles.Contains("Admin"));
}
else
{
artistOverviewDto = _artistsService.GetArtistBySlug(slug, "", false);
}
return Ok(artistOverviewDto);
}
[Authorize]
[HttpPost]
public async Task<IActionResult> CreateArtist([FromBody] ArtistCreateDto artistCreateDto)
{
if (artistCreateDto == null) return BadRequest();
if (!ModelState.IsValid) return BadRequest(ModelState);
var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByNameAsync(username);
var artistOverviewDto = await _artistsService.AddNewArtist(user.Id, artistCreateDto);
if (artistOverviewDto == null) return NotFound();
return CreatedAtRoute("GetArtist", new {artistOverviewDto.Slug}, artistOverviewDto);
}
}
I have 3 methods. One to get a list of artists, one to get a single artist and finally, one to create a new artist (you need to be logged in for that one).
How would you improve the code above? Readability of code is very important to me, and right now I don't feel it particularly reads well.