User controller for a .net core WebAPI dating appWebAPI controllerController for repository of membersSimple...

How do I deal with a powergamer in a game full of beginners in a school club?

Does splitting a potentially monolithic application into several smaller ones help prevent bugs?

Algorithm to convert a fixed-length string to the smallest possible collision-free representation?

Is Gradient Descent central to every optimizer?

What to do when during a meeting client people start to fight (even physically) with each others?

How to pass a string to a command that expects a file?

Is there any way to click on 6th item of this list

How to create a hard link to an inode (ext4)?

Can one live in the U.S. and not use a credit card?

Can Mathematica be used to create an Artistic 3D extrusion from a 2D image and wrap a line pattern around it?

Is this combination of Quivering Palm and Haste RAW?

infinitive telling the purpose

Finding algorithms of QGIS commands?

How did Alan Turing break the enigma code using the hint given by the lady in the bar?

Am I not good enough for you?

Built-In Shelves/Bookcases - IKEA vs Built

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

Distinction between apt-cache and dpkg -l

Does "variables should live in the smallest scope as possible" include the case "variables should not exist if possible"?

Bash script should only kill those instances of another script's that it has launched

Unreachable code, but reachable with exception

Why is this plane circling around the LKO airport every day?

Leftbar without indentation

Set and print content of environment variable in cmd.exe subshell?



User controller for a .net core WebAPI dating app


WebAPI controllerController for repository of membersSimple and reusable system for user registration and tracking and auto-updatesWPF async ObservableTaskQueue classDatabase logger for ASP.NET CoreMapper made specifically to work with DapperA controller on a .net core API.NET Core MVC - Future proof Hashing of passwordsasp.net core - get User at Service LayerAuto register Func<T> for .net core dependecy injection













2












$begingroup$


I have this user controller that follows the repository pattern. It works perfect, but is it easy to understand? Is this good quality work?



using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp_API.Data;
using DatingApp_API.DataTransferObjects;
using DatingApp_API.Helpers;
using DatingApp_API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DatingApp_API.Controllers
{
[ServiceFilter(typeof(LogUserActivity))]
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IDatingRepository _repo;
private readonly IMapper _mapper;
public UsersController(IDatingRepository repo, IMapper mapper)
{
_mapper = mapper;
_repo = repo;
}

[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

var userFromRepo = await _repo.GetUser(currentUserId);

userParams.UserId = currentUserId;

if(string.IsNullOrEmpty(userParams.Gender))
{
userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
}

var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);

Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
return Ok(usersToReturn);
}

[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> GetUser(int id)
{
var user = await _repo.GetUser(id);
var userToReturn = _mapper.Map<UserForDetailedDTO>(user);

return Ok(userToReturn);
}

[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
{
if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();

var userFromRepo = await _repo.GetUser(id);

_mapper.Map(userForUpdateDTO, userFromRepo);

if(await _repo.SaveAll())
return NoContent();

throw new Exception($"Updating user {id} failed on save");
}

[HttpPost("{id}/like/{recipientId}")]
public async Task<IActionResult> LikeUser(int id, int recipientId)
{
if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();

var like = await _repo.GetLike(id, recipientId);

if(like != null)
return BadRequest("You already like this user");

if(await _repo.GetUser(recipientId) == null)
return NotFound();

like = new Like
{
LikerId = id,
LikeeId = recipientId
};

_repo.Add<Like>(like);

if(await _repo.SaveAll())
return Ok();

return BadRequest("Failed to like user");
}

}
}









share|improve this question









New contributor




Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    2












    $begingroup$


    I have this user controller that follows the repository pattern. It works perfect, but is it easy to understand? Is this good quality work?



    using System;
    using System.Collections.Generic;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using AutoMapper;
    using DatingApp_API.Data;
    using DatingApp_API.DataTransferObjects;
    using DatingApp_API.Helpers;
    using DatingApp_API.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;

    namespace DatingApp_API.Controllers
    {
    [ServiceFilter(typeof(LogUserActivity))]
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
    private readonly IDatingRepository _repo;
    private readonly IMapper _mapper;
    public UsersController(IDatingRepository repo, IMapper mapper)
    {
    _mapper = mapper;
    _repo = repo;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
    {
    var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

    var userFromRepo = await _repo.GetUser(currentUserId);

    userParams.UserId = currentUserId;

    if(string.IsNullOrEmpty(userParams.Gender))
    {
    userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
    }

    var users = await _repo.GetUsers(userParams);
    var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);

    Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
    return Ok(usersToReturn);
    }

    [HttpGet("{id}", Name = "GetUser")]
    public async Task<IActionResult> GetUser(int id)
    {
    var user = await _repo.GetUser(id);
    var userToReturn = _mapper.Map<UserForDetailedDTO>(user);

    return Ok(userToReturn);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
    {
    if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
    return Unauthorized();

    var userFromRepo = await _repo.GetUser(id);

    _mapper.Map(userForUpdateDTO, userFromRepo);

    if(await _repo.SaveAll())
    return NoContent();

    throw new Exception($"Updating user {id} failed on save");
    }

    [HttpPost("{id}/like/{recipientId}")]
    public async Task<IActionResult> LikeUser(int id, int recipientId)
    {
    if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
    return Unauthorized();

    var like = await _repo.GetLike(id, recipientId);

    if(like != null)
    return BadRequest("You already like this user");

    if(await _repo.GetUser(recipientId) == null)
    return NotFound();

    like = new Like
    {
    LikerId = id,
    LikeeId = recipientId
    };

    _repo.Add<Like>(like);

    if(await _repo.SaveAll())
    return Ok();

    return BadRequest("Failed to like user");
    }

    }
    }









    share|improve this question









    New contributor




    Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      2












      2








      2


      1



      $begingroup$


      I have this user controller that follows the repository pattern. It works perfect, but is it easy to understand? Is this good quality work?



      using System;
      using System.Collections.Generic;
      using System.Security.Claims;
      using System.Threading.Tasks;
      using AutoMapper;
      using DatingApp_API.Data;
      using DatingApp_API.DataTransferObjects;
      using DatingApp_API.Helpers;
      using DatingApp_API.Models;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;

      namespace DatingApp_API.Controllers
      {
      [ServiceFilter(typeof(LogUserActivity))]
      [Authorize]
      [Route("api/[controller]")]
      [ApiController]
      public class UsersController : ControllerBase
      {
      private readonly IDatingRepository _repo;
      private readonly IMapper _mapper;
      public UsersController(IDatingRepository repo, IMapper mapper)
      {
      _mapper = mapper;
      _repo = repo;
      }

      [HttpGet]
      public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
      {
      var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

      var userFromRepo = await _repo.GetUser(currentUserId);

      userParams.UserId = currentUserId;

      if(string.IsNullOrEmpty(userParams.Gender))
      {
      userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
      }

      var users = await _repo.GetUsers(userParams);
      var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);

      Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
      return Ok(usersToReturn);
      }

      [HttpGet("{id}", Name = "GetUser")]
      public async Task<IActionResult> GetUser(int id)
      {
      var user = await _repo.GetUser(id);
      var userToReturn = _mapper.Map<UserForDetailedDTO>(user);

      return Ok(userToReturn);
      }

      [HttpPut("{id}")]
      public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
      {
      if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
      return Unauthorized();

      var userFromRepo = await _repo.GetUser(id);

      _mapper.Map(userForUpdateDTO, userFromRepo);

      if(await _repo.SaveAll())
      return NoContent();

      throw new Exception($"Updating user {id} failed on save");
      }

      [HttpPost("{id}/like/{recipientId}")]
      public async Task<IActionResult> LikeUser(int id, int recipientId)
      {
      if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
      return Unauthorized();

      var like = await _repo.GetLike(id, recipientId);

      if(like != null)
      return BadRequest("You already like this user");

      if(await _repo.GetUser(recipientId) == null)
      return NotFound();

      like = new Like
      {
      LikerId = id,
      LikeeId = recipientId
      };

      _repo.Add<Like>(like);

      if(await _repo.SaveAll())
      return Ok();

      return BadRequest("Failed to like user");
      }

      }
      }









      share|improve this question









      New contributor




      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I have this user controller that follows the repository pattern. It works perfect, but is it easy to understand? Is this good quality work?



      using System;
      using System.Collections.Generic;
      using System.Security.Claims;
      using System.Threading.Tasks;
      using AutoMapper;
      using DatingApp_API.Data;
      using DatingApp_API.DataTransferObjects;
      using DatingApp_API.Helpers;
      using DatingApp_API.Models;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;

      namespace DatingApp_API.Controllers
      {
      [ServiceFilter(typeof(LogUserActivity))]
      [Authorize]
      [Route("api/[controller]")]
      [ApiController]
      public class UsersController : ControllerBase
      {
      private readonly IDatingRepository _repo;
      private readonly IMapper _mapper;
      public UsersController(IDatingRepository repo, IMapper mapper)
      {
      _mapper = mapper;
      _repo = repo;
      }

      [HttpGet]
      public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
      {
      var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

      var userFromRepo = await _repo.GetUser(currentUserId);

      userParams.UserId = currentUserId;

      if(string.IsNullOrEmpty(userParams.Gender))
      {
      userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
      }

      var users = await _repo.GetUsers(userParams);
      var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);

      Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
      return Ok(usersToReturn);
      }

      [HttpGet("{id}", Name = "GetUser")]
      public async Task<IActionResult> GetUser(int id)
      {
      var user = await _repo.GetUser(id);
      var userToReturn = _mapper.Map<UserForDetailedDTO>(user);

      return Ok(userToReturn);
      }

      [HttpPut("{id}")]
      public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
      {
      if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
      return Unauthorized();

      var userFromRepo = await _repo.GetUser(id);

      _mapper.Map(userForUpdateDTO, userFromRepo);

      if(await _repo.SaveAll())
      return NoContent();

      throw new Exception($"Updating user {id} failed on save");
      }

      [HttpPost("{id}/like/{recipientId}")]
      public async Task<IActionResult> LikeUser(int id, int recipientId)
      {
      if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
      return Unauthorized();

      var like = await _repo.GetLike(id, recipientId);

      if(like != null)
      return BadRequest("You already like this user");

      if(await _repo.GetUser(recipientId) == null)
      return NotFound();

      like = new Like
      {
      LikerId = id,
      LikeeId = recipientId
      };

      _repo.Add<Like>(like);

      if(await _repo.SaveAll())
      return Ok();

      return BadRequest("Failed to like user");
      }

      }
      }






      c# controller repository asp.net-core






      share|improve this question









      New contributor




      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 15 mins ago









      200_success

      130k17153419




      130k17153419






      New contributor




      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 29 mins ago









      AndreAndre

      111




      111




      New contributor




      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Andre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Andre is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215276%2fuser-controller-for-a-net-core-webapi-dating-app%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Andre is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Andre is a new contributor. Be nice, and check out our Code of Conduct.













          Andre is a new contributor. Be nice, and check out our Code of Conduct.












          Andre is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215276%2fuser-controller-for-a-net-core-webapi-dating-app%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Webac Holding Inhaltsverzeichnis Geschichte | Organisationsstruktur | Tochterfirmen |...

          What's the meaning of a knight fighting a snail in medieval book illustrations?What is the meaning of a glove...

          Salamanca Inhaltsverzeichnis Lage und Klima | Bevölkerungsentwicklung | Geschichte | Kultur und...