【发布时间】:2019-06-16 19:31:03
【问题描述】:
我不知道我的 LINQ 查询出了什么问题,一切看起来都很好,但我在以下代码中遇到了上述错误:
if (!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);
}
}
}
【问题讨论】:
-
首先尝试
dbcontext.AndroidUser.Where(user => user.Equals (value.UserName)).ToList().Any();和dbcontext.AndroidUser.Add(user); -
@FlavioFrancisco 我按照你说的做了,但它给出了同样的错误。
-
我添加了这个方法,然后在我的 if 条件中调用它,“ public bool checkUserName(string uname) { AndroidUser user = (from e in dbcontext.AndroidUser where e.UserName == uname select e) .FirstOrDefault(); Console.Write(user.UserName); if (user == null) { return true; } else { return false; } } “它有效,但现在它给出了另一个错误
-
错误是值为空,但我已经在测试时为用户名和密码变量赋值
-
错误可能在
Console.Write(user.UserName);这一行。如果没有找到用户,那么它将为空,您无法对其进行评估。
标签: asp.net-web-api asp.net-core-webapi