【发布时间】:2020-02-02 09:28:30
【问题描述】:
我在一个聊天网站上工作,我已经收到这个讨厌的错误有一段时间了,真的不知道它可能是什么。 我有这个模型类:
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 页面的一部分。 这是我的聊天视图控制器:
public class ChatController: Controller
{
public ChatController()
{
}
public IActionResult Chat(ChatModel model)
{
return View(model);
}
}
以及对控制器操作的调用:
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);
}
由于某种原因,当我调用 Chat 视图的控制器方法时,它会抛出以下异常:
InvalidOperationException:无法创建类型的实例 'Microsoft.AspNetCore.Http.HttpContext'。模型绑定的复杂类型 不能是抽象类型或值类型,并且必须具有无参数 构造函数。或者,将“HttpContext”属性设置为 “Chatter.UI.Web.Views.Chat.ChatModel”中的非空值 构造函数。 Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext 绑定上下文)
最奇怪的是,我什至没有在 ChatModel 类上使用 HttpContext。我曾尝试使用 DI 在我的班级中注入 IHttpContextAccessor(尽管我看不出这有什么帮助,但我已经将其视为在线解决方案);它没有用。我还尝试在启动时为 HttpContext 添加一个单例,但无济于事。任何关于正在发生的事情的想法将不胜感激。
【问题讨论】:
-
PageModel 是一个什么样的类?
-
据我所知,您的
ChatModal类应该有默认的无参数构造函数 -
为什么 ChatModel 是 PageModel?似乎您正在以一种奇怪的方式混合 RazorPages 和 Mvc
-
我是 Razor 页面的新手,Razor 页面模型不能与 MVC 模型互换吗?
标签: c# asp.net asp.net-mvc visual-studio asp.net-core