无法将“system.string”类型的对象强制转换为“system.int32”类型

unguejic  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(488)

我是一个新的开发人员和全新的azuresql数据库,我已经发布了一个应用程序,它在我的本地机器上运行良好。但我得到铸造错误时,试图登录发布应用程序,我不知道为什么。

这就是错误

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
   at Microsoft.Data.SqlClient.SqlBuffer.get_Int32()
   at Microsoft.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
   at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at MydateAPI.Repositories.Repo.AuthRepository.Login(String username, String password) in C:\MyProjects\MyDate\MydateAPI\Repositories\Repo\AuthRepository.cs:line 22
   at MydateAPI.Controllers.AuthController.Login(UserForLoginDto userForLoginDTO) in C:\MyProjects\MyDate\MydateAPI\Controllers\AuthController.cs:line 67
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

这是登录方法

[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto userForLoginDTO)
{
    //throw new Exception("Computer says No!");

    var userFromRepo = await _repo.Login(userForLoginDTO.Username.ToLower(), userForLoginDTO.Password);

    if (userFromRepo == null)
        return Unauthorized();

    var claims = new[]
    {
        new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
        new Claim(ClaimTypes.Name, userFromRepo.Username)
    };

    //Created a security Key for the signin credential and encrypted the key
    var key = new SymmetricSecurityKey(Encoding.UTF8
        .GetBytes(_config.GetSection("AppSettings:Token").Value));

    //Sign in credential
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

    //Security token descriptor to contain claim, expiry date of token and signin  credential
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.Now.AddDays(1),
        SigningCredentials = creds
    };

    var tokenHandler = new JwtSecurityTokenHandler();

    var token = tokenHandler.CreateToken(tokenDescriptor);

    var user = _mapper.Map<UserForListDto>(userFromRepo);

    //return the token as an object to the client
    return Ok(new
    {
        token = tokenHandler.WriteToken(token),
        user
    });

}

我的存储库中的登录方法

public async Task<User> Login(string username, string password)
{
    //var user = await _context.Users.Include(p => p.Photos).FirstOrDefaultAsync(x => x.Username == username);
    var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == username);

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

    if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
        return null;

    return user;

}

错误出现在authcontroller login的第67行(下面)

var userFromRepo = await _repo.Login(userForLoginDTO.Username.ToLower(), userForLoginDTO.Password);

以及我的存储库登录的第22行(下面)

var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == username);

但是我看不到我在哪里把'system.string'类型转换成'system.int32'。
我已在azure资源组中附加了sql数据库的快照。
我可以注册一个新用户,但不能登录。但在我的本地机器上,我可以注册和登录没有任何错误。
需要帮助吗

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题