我正在一个聊天网站上工作,我已经收到这个讨厌的错误有一段时间了,真的不知道它可能是什么。 我有这个模型类:
public class ChatModel : PageModel
{
public string UserName { get; set; }
public ICollection<string> Espectators { get; set; }
public ICollection<string> Chatters { get; set; }
public string Mediator { get; set; }
public Conversation Conversation{ get; set; }
public Lazy<IConcurrentCaching> _cache { get; set; }
public ChatModel()
{
}
public ChatModel(string connString, string bulkTime, string username, ICollection<string> espectators = null, ICollection<string> chatters = null, string mediator = null, string conversationName = null)
{
//build the class, boring stuff
}
public void OnGet()
{
}
}
此模型是 Razor 页面的一部分。 这是我的聊天 View Controller :
public class ChatController: Controller
{
public ChatController()
{
}
public IActionResult Chat(ChatModel model)
{
return View(model);
}
}
以及对 Controller 操作的调用:
public IActionResult CreateChat(string username, string conversationName)
{
if (_cache.Value.Get<List<string>>("ChatList") == null)
{
_cache.Value.Set<List<string>>("ChatList", new List<string>(), 1440);
}
ChatModel model = new ChatModel(_op.Value.ConnectionString, _op.Value.BulkLoadCacheTimeInMinutes, username, conversationName: conversationName);
model.Chatters.Add(username);
return RedirectToAction("Chat","Chat", model);
}
由于某种原因,当我调用聊天 View 的 Controller 方法时,它抛出以下异常:
InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.Http.HttpContext'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, set the 'HttpContext' property to a non-null value in the 'Chatter.UI.Web.Views.Chat.ChatModel' constructor. Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
最奇怪的是我什至没有在 ChatModel 类上使用 HttpContext。我尝试使用 DI 在我的类上注入(inject) IHttpContextAccessor (尽管我不知道这有什么帮助,但我已经看到这是一个在线解决方案);它不起作用。我还尝试在启动时为 HttpContext 添加单例,但无济于事。任何有关正在发生的事情的想法将不胜感激。
最佳答案
您不应组合 PageModel
和 Controller
。
如错误所示,模型绑定(bind)复杂类型不能是抽象或值类型,并且必须具有无参数构造函数。对于继承PageModel
的ChatModel
来说,是abstract
类。
创建一个新的单独类以在 Controller
操作中使用。
关于c# - 无法创建类型 'Microsoft.AspNetCore.Http.HttpContext' 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229667/