Home > Blockchain >  Asp.net Core Object reference not set to an instance of an object
Asp.net Core Object reference not set to an instance of an object

Time:02-26

ASP.NET CORE API

The logged in user gives an error in the code below while adding a photo. Can anybody help?

var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) 

This code gives an error. Help me

Object reference not set to an instance of an object

PhotosController.cs

    [HttpPost]
        public ActionResult AddPhotoForCity(int cityId,[FromForm]PhotoForCreationDto photoForCreationDto)
        {
            
            var city = _appRepository.GetCityById(cityId);

            
            if (city == null)
            {
                return BadRequest("Could not find the city.");
            }

            
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

             karşılaştırmak gibi
            if (currentUserId != city.UserId)
            {
                return Unauthorized();
            }

            var file = photoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var steam = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name,steam)
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            photoForCreationDto.Url = uploadResult.Url.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            
            var photo = _mapper.Map<Photo>(photoForCreationDto);
            photo.City = city;

            
            if (!city.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            city.Photos.Add(photo);

            
            if (_appRepository.SaveAll())
            {
                //eklenen fotoğrafı döndürüyoruz
                var photoToRetun = _mapper.Map<Photo>(photoForCreationDto);
                return CreatedAtRoute("GetPhoto", new {id = photo.Id}, photoToRetun);
            }

            return BadRequest("Cloud not add the photo");

        }

AuthController.cs

    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private IAuthRepository _authRepository;
        private IConfiguration _configuration;

        public AuthController(IAuthRepository authRepository, IConfiguration configuration)
        {
            _authRepository = authRepository;
            _configuration = configuration;
        }
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto)
        {
            if (await _authRepository.UserExists(userForRegisterDto.UserName))
            {
                ModelState.AddModelError("UserName", "Username already exists");
            }
            
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userToCreate = new User
            {
                UserName = userForRegisterDto.UserName
            };

            var createdUser = await _authRepository.Register(userToCreate, userForRegisterDto.Password);
            return StatusCode(201);
        }

        [HttpPost("login")]
        public async Task<ActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            var user = await _authRepository.Login(userForLoginDto.UserName, userForLoginDto.Password);

            if (user == null)
            {
                return Unauthorized();
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName)
                }),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key)
                    , SecurityAlgorithms.HmacSha512Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return Ok(tokenString);
        }


    }

CodePudding user response:

From the above code snippet you have shared, they mostly likely reason you are getting this error is because the user is not logged in, and hence this line of code

User.FindFirst(ClaimTypes.NameIdentifier).Value

is throwing an exception. You could either do it like this.

User.FindFirst(ClaimTypes.NameIdentifier)?.Value

Or

[HttpPost]
[Authorize] // make sure you authorize your action method by adding this attribute and
            // only allow logged in user to access it. 
public ActionResult AddPhotoForCity(int cityId,[FromForm]PhotoForCreationDto photoForCreationDto)
{
}

CodePudding user response:

try this one:

var currentUserId = int.Parse(User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
  • Related