System.InvalidOperationException(尝试评估LINQ查询参数表达式时引发了异常)

时间:2019-06-15 13:39:41

标签: asp.net-web-api asp.net-core-webapi

我不知道我的LINQ查询出了什么问题,一切看起来都很好,但是我在以下代码上遇到了错误:

如果(!dbcontext.AndroidUser.Any(user => user.Equals(value.UserName)))

这是我关于RegisterController.cs的完整代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using APITesting.Models;
using APITesting.Utils;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace APITesting.Controllers
{
[Route("api/[controller]")]
public class RegisterController : Controller
{
    NoNameRestaurantContext dbcontext = new NoNameRestaurantContext();

    // POST api/<controller>
    [HttpPost]
    public string Post([FromBody]AndroidUser value)
    {
        //First we need to check that user is existing in database.
        if (!dbcontext.AndroidUser.Any(user => user.Equals                (value.UserName)))
        {
            AndroidUser user = new AndroidUser();
            user.UserName = value.UserName;
            user.Hash = Convert.ToBase64String(Common.GetRandomHash(16));
            user.Password = Convert.ToBase64String(Common.HashPassword(
                Encoding.ASCII.GetBytes(value.Password),
                Convert.FromBase64String(user.Hash)));

            //Save to Database

            try
            {
                dbcontext.Add(user);
                dbcontext.SaveChanges();
                return JsonConvert.SerializeObject("Register Successfully");
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(ex.Message);
            }
        }
        else
        {
            return JsonConvert.SerializeObject("User is existing in Database");
        }

    }

  }
}

以及用于将密码转换为hashPassword的Common.cs类。

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Security.Cryptography;
 using System.Threading.Tasks;

 namespace APITesting.Utils
 {
 public class Common
 {
    /*
     * 
     * FUNCTION TO CREATE RANDOM HASH STRING
     * 
     */
    public static byte[] GetRandomHash(int length)
    {
        var random = new RNGCryptoServiceProvider();
        byte[] hash = new byte[length];
        random.GetNonZeroBytes(hash);
        return hash;
    }
    /*
     * 
     * FUNCTION TO CREATE PASSWORD WITH HASH
     * 
     */
    public static byte[] HashPassword(byte[] password, byte[] hash)
    {
        HashAlgorithm algorithm = new SHA256Managed();
        byte[] plainTextWithHashByte = new byte[password.Length + hash.Length];
        for (int i = 0; i < password.Length; i++)
        {
            plainTextWithHashByte[i] = password[i];
        }
        for (int i = 0; i < hash.Length; i++)
        {
            plainTextWithHashByte[password.Length + i] = hash[i];
        }
        return algorithm.ComputeHash(plainTextWithHashByte);
    }
  }
}

我正在关注本教程:https://www.youtube.com/watch?v=b6T0_j7I9CE

1 个答案:

答案 0 :(得分:0)

我尝试使用以下代码重现您的问题,并且成功了。确保将对象AndroidUser发送到您的方法。

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
using WebApplicationLab.Models;
using WebApplicationLab.Utils;

namespace WebApplicationLab.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase
    {
       private readonly AppDbContext _context;

       //Inject your DbContext object instead of create a new instance.
       public RegisterController(AppDbContext context)
       {
          _context = context;
       }

       public string Post([FromBody]User value)
       {
           //Make sure that your object `User` is being sent to your method. 
           if(value == null) 
           {   
              return JsonConvert.SerializeObject("Please inform a valid user!");
           }

          if (!IsUserExists(value.UserName))
          {
              var random = new Random();
              var hash = Common.GetRandomHash(random.Next(1, 100));

              var user = new User()
              {
                  UserName = value.UserName,
                  Hash = Convert.ToBase64String(hash),
                  Password = Convert.ToBase64String(Common.HashPassword(Encoding.ASCII.GetBytes(value.Password), hash))
               };

            _context.Users.Add(user);
            _context.SaveChanges();

            return JsonConvert.SerializeObject("Register Successfully");
        }

          return JsonConvert.SerializeObject("User already exists.");
       }

       private bool IsUserExists(string userName)
       {
           return _context.Users.Any(x => x.UserName.Equals(userName));
        }
    }
}

我的模型班:

[Table("Users")]
public class User
{     
    [Key]
    public string UserName { get; set; }

    public string Hash { get; set; }

    public string Password { get; set; }
}