【发布时间】:2020-06-13 02:43:08
【问题描述】:
我正在 dot net core 中使用 UseInMemoryDatabase 测试以下 Web api 代码。
控制器
[HttpGet("{id}", Name = "GetPasscode")]
public IActionResult GetPasscode(SqlBytes id)
{
if (id == null)
{
throw new ArgumentException("Invalid address");
}
var p = _context.AddressPasscodes.FirstOrDefault(a => a.Address == id);
if (p == null)
{
p = new AddressPasscode{ Address = id, Passcode = 123 };
_context.AddressPasscodes.Add(p);
_context.SaveChanges();
};
return new ObjectResult(p);
}
型号
public class AddressPasscode
{
public SqlBytes Address { get; set; }
public int Passcode { get; set; }
}
但是,在测试http://localhost:5000/api/passcode/1时出现如下运行时异常
SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
System.Data.SqlTypes.SqlBytes.get_Length()
SqlNullValueException:数据为空。不能对 Null 值调用此方法或属性。
System.Data.SqlTypes.SqlBytes.get_Length()
Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter(Func getter,对象目标)
Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy+Enumerator.GetModel(对象容器,ModelMetadata 属性)
Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy+Enumerator+c__DisplayClass10_0.b__1()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationEntry.get_Model()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy 策略)
【问题讨论】:
-
我认为 p 是空的。使用这个
if (p != null && p.Passcode == 0)
标签: asp.net asp.net-web-api .net-core