在过去的2周中,我一直在努力使其正常运行,但似乎找不到问题。当我单击一个用户与其聊天时,似乎并没有在两者之间创建聊天室。我遵循了该教程https://pusher.com/tutorials/chat-aspnet/,但是编辑了一些类似我的数据库的内容。调试后,当我单击其中一个用户链接时,它似乎什么都不做。
我尝试重命名所有内容并重新开始
使用javascript查看我的视图
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-3">
<aside class="main visible-md visible-lg">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default users__bar">
<div class="panel-heading users__heading">
Contacts (@ViewBag.allUsers.Count)
</div>
<div class="__no__chat__">
<p>Select a contact to chat with</p>
</div>
<div class="panel-body users__body">
<ul id="contacts" class="list-group">
@foreach (var user in @ViewBag.allUsers)
{
<a class="user__item contact-@user.Id" href="#" data-contact-id="@user.Id" data-contact-name="@user.FirstName">
<li>
<div class="avatar">
<img src="@Url.Content("~/Content/no_avatar.png")">
</div>
<span>@user.FirstName</span>
<div class="status-bar"></div>
</li>
</a>
}
</ul>
</div>
</div>
</div>
</div>
</aside>
</div>
<div class="col-xs-12 col-md-9 chat__body">
<div class="row">
<div class="col-xs-12">
<ul class="list-group chat__main"></ul>
</div>
<div class="chat__type__body">
<div class="chat__type">
<textarea id="msg_box" placeholder="Type your message"></textarea>
<button class="btn btn-primary" id="sendMessage">Send</button>
</div>
</div>
<div class="chat__typing">
<span id="typerDisplay"></span>
</div>
</div>
</div>
</div>
</div>
<script>
let currentContact = null; // Holds current contact
let newMessageTpl =
`<div>
<div id="msg-{{id}}" class="row __chat__par__">
<div class="__chat__">
<p>{{body}}</p>
<p class="delivery-status">Delivered</p>
</div>
</div>
</div>`;
// select contact to chat with
$('.user__item').click(function(e) {
e.preventDefault();
currentContact = {
Id: $(this).data('contact-id'),
FirstName: $(this).data('contact-name'),
};
$('#contacts').find('li').removeClass('active');
$('#contacts .contact-' + currentContact.Id).find('li').addClass('active');
getChat(currentContact.Id);
});
// get chat data
function getChat(contact_id) {
$.get("/contact/conversations/" + contact_id)
.done(function(resp) {
var chat_data = resp.data || [];
loadChat(chat_data);
});
}
...
我的控制器:
public ActionResult Index()
{
if (Session["UserID"] == null)
{
return Redirect("/");
}
//var currentUser = (Models.tblUser) Session["UserID"];
using (var db = new Models.ChatContext())
{
int currentUserId = (int) Session["UserID"];
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
ViewBag.allUsers = db.Users.Where(u => u.Id != currentUser.Id).ToList();
ViewBag.currentUser = currentUser;
}
return View();
}
public JsonResult ConversationWithContact(int contact)
{
if (Session["UserID"] == null)
{
return Json(new {status = "error", message = "User is not logged in"});
}
var currentUser = (Models.tblUser)Session["UserID"];
var conversations = new List<Models.tblMessage>();
using (var db = new Models.ChatContext())
{
conversations = db.Conversations.Where(c => (c.receiverId == currentUser.Id
&& c.senderId == contact) ||
(c.receiverId == contact
&& c.senderId == currentUser.Id))
.OrderBy(c => c.created_at)
.ToList();
}
return Json(
new {status = "success", data = conversations},
JsonRequestBehavior.AllowGet
);
}
我的消息模型和聊天上下文:
public class ChatContext : DbContext
{
public ChatContext() : base("TrinityEntities")
{
}
public static ChatContext Create()
{
return new ChatContext();
}
public DbSet<tblUser> Users { get; set; }
public DbSet<tblMessage> Conversations { get; set; }
}
public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}
public enum messageStatus
{
Sent,
Delivered
}
public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}
我的routeconfig:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
);
//routes.MapRoute(
// name: "Default",
// url: "",
// defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
//);
routes.MapRoute(
name: "Profile",
url: "profile",
defaults: new { controller = "Profile", action = "Index" }
);
routes.MapRoute(
name: "Home",
url: "Home",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "ChatRoom",
url: "chat",
defaults: new { controller = "Chat", action = "Index" }
);
routes.MapRoute(
name: "GetContactConversations",
url: "contact/conversations/{contact}",
defaults: new { controller = "Chat", action = "ConversationWithContact", contact = "" }
);
routes.MapRoute(
name: "PusherAuth",
url: "pusher/auth",
defaults: new { controller = "Auth", action = "AuthForChannel" }
);
routes.MapRoute(
name: "SendMessage",
url: "send_message",
defaults: new { controller = "Chat", action = "SendMessage" }
);
routes.MapRoute(
name: "MessageDelivered",
url: "message_delivered/{message_id}",
defaults: new { controller = "Chat", action = "MessageDelivered", message_id = "" }
);
答案 0 :(得分:1)
ChatContext位下面的指令中可能会漏掉一行:
“要检索消息,我们将为 / contact`` / conversations / {contact}。此路线将接受联系人 ID,检索当前用户和联系人之间的消息,然后 返回JSON响应中的消息。 “
当前,在javascript中,getChat()函数将请求发送至/contact/conversation/{contactId}
。对于MVC项目,默认路由格式为/{controllerName}/{actionName}/{parameter}
。因此,您的javascript中的调用当前会查找名为ContactController
的控制器,然后在名为Conversation
的控制器上执行操作。如您所知,这些在您的项目中目前尚不存在,因此您需要在routeConfig中设置一条路由,该路由可以理解传入的请求并将其指向您希望去的地方:
routes.MapRoute(
name: "ChatRoom",
url: "chat/conversation/{contact}",
defaults: new { controller = "Chat", action = "ConversationWithContact" }
);
这应该可以解决您的问题。但是,当您刚刚学习时,我认为值得一提的是,尽管对于小型应用程序来说不错,但是当应用程序扩展后,手动映射这样的路由可能会导致混乱,因为您可以使用数十种不同名称的路由来指向控制器和操作。不可能猜到。如果代码符合/controllerName/actionName