Asp.net web api 如何在ASP.net核心web应用程序中实现signalR中的组

Asp.net web api 如何在ASP.net核心web应用程序中实现signalR中的组,asp.net-web-api,signalr,signalr-hub,signalr.client,asp.net-core-signalr,Asp.net Web Api,Signalr,Signalr Hub,Signalr.client,Asp.net Core Signalr,我使用信号器组,每当用户更改数据时,组中的每个用户都可以实时看到更改的数据 我在这个项目中使用了ASP.net核心web应用程序Template 控制器的代码为: public class PatientCollectionsController : ControllerBase { private readonly IHubContext<GroupHub> groupHub; public PatientCollectionsController(Func<

我使用信号器组,每当用户更改数据时,组中的每个用户都可以实时看到更改的数据

我在这个项目中使用了ASP.net核心web应用程序Template

控制器的代码为:

public class PatientCollectionsController : ControllerBase
{
    private readonly IHubContext<GroupHub> groupHub;

    public PatientCollectionsController(Func<string, IPatientCollectionsService> serviceResolver, IConfiguration configuration, ILogger<PatientCollectionsModel> logger,
        IHubContext<GroupHub> grpHub)
    {
        this.dbservice = serviceResolver(configuration.GetValue<string>("CollectionsDbChoice").ToLower());
        this.logger = logger;
        this.groupHub = grpHub;
    }

    // GET: api/<PatientCollectionsController>
    [HttpGet]
    public IActionResult Get()
    {
        HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

        try
        {
            return Ok(dbservice.GetPatientCollections());
        }
        catch (Exception ex)
        {
            logger.LogError("failed to get Patient Collections", ex.Message, ex.StackTrace);
            logger.LogInformation(ex.Message, ex.StackTrace);
            return StatusCode(500, "Internal server error");
        }
    }
    
    // PUT api/<PatientCollectionsController>/5
    [HttpPut("{id}")]
    public void Put(string id, [FromBody] PatientCollectionsModel value)
    {
        try
        { 
            dbservice.PutPatientCollection(value);
        }
        catch(Exception ex)
        {
            logger.LogError("failed to put Patient Collections", ex.Message, ex.StackTrace);
            logger.LogInformation(ex.Message, ex.StackTrace);
            StatusCode(500, "Internal server error");
        }
    }


    static readonly string[] scopeRequiredByApi = new string[] { "access_as_signedin_user" };
    private IPatientCollectionsService dbservice;
    private ILogger<PatientCollectionsModel> logger;
}
有谁能建议我应该怎么做才能让它工作,以及如何将用户发送到不同的组

wait Groups.AddToGroupAsync(Context.ConnectionId,group);
wait Groups.RemoveFromGroupAsync(Context.ConnectionId,group);
众所周知,连接是通过
AddToGroupAsync
RemoveFromGroupAsync
方法添加到组或从组中删除的。因此,要管理(添加/删除)组中的用户,首先应该获取用户的
连接ID

在Hub的
OnConnectedAsync
方法中,可以通过上下文获取ConnectionID。然后,将
ConnectionID
UserName
存储到数据库中

在集线器的OnDisconnectedAsync方法中,如果用户已断开连接,请从表中删除该用户

之后,您可以根据
用户名
查找
连接ID
,并使用
AddToGroupAsync
RemoveFromGroupAsync
方法将用户添加/删除到组中

//要求使用Microsoft.AspNetCore.signal;
//需要使用Microsoft.AspNetCore.Authorization;
[授权]
公共类聊天室:聊天室
{ 
私有只读应用程序DBContext _context;//DB context
公共聊天中心(ApplicationDbContext上下文)
{
_上下文=上下文;
}
公共覆盖任务OnConnectedAsync()
{ 
//获取登录的用户名。
var IdentityName=Context.User.Identity.Name;
SignalRUser user=new SignalRUser(){ConnectionID=Context.ConnectionID,UserName=IdentityName};
_context.SignalRUser.Add(用户);
_SaveChanges();
返回base.OnConnectedAsync();
} 
公共覆盖异步任务OnDisconnectedAsync(异常)
{
var IdentityName=Context.User.Identity.Name;
var user=_context.SignalRUser.Where(c=>c.UserName==IdentityName.FirstOrDefault();
//如果用户断开连接,请删除用户
如果(用户!=null)
{
_context.SignalRUser.Remove(用户);
_SaveChanges();
}
等待base.OnDisconnectedAsync(异常);
}
}
public class PatientCollectionsDBService : IPatientCollectionsService
{
    #region ctor
    public PatientCollectionsDBService(IDatabaseSettings settings)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString);
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
        patientCollectionsTable = tableClient.GetTableReference("PatientCollections");
        patientCollectionsTable.CreateIfNotExists();
    }
    #endregion

    #region IPatientCollectionsService Impl
    public List<PatientCollectionsModel> GetPatientCollections()
    {
        TableContinuationToken token = null;
        var pc = new List<PatientCollectionsModel>();
        do
        {
            var tableQuery = new TableQuery<DynamicTableEntity>
            {
                FilterString = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "current")
            };
            var queryResult = patientCollectionsTable.ExecuteQuerySegmented(tableQuery, token);
            foreach (var entity in queryResult)
            {
                pc.Add(new PatientCollectionsModel
                {
                    Id = entity.RowKey,
                    FirstName = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.FirstName)]),
                    PtId = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.PtId)]),
                    DOS = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.DOS)]),
                    PatientBalance = (float)entity.Properties[nameof(PatientCollectionsModel.PatientBalance)].DoubleValue,
                    EOB = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.EOB)]),
                    PhoneNo = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.PhoneNo)]),
                    BalanceCurrent = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceCurrent)]),
                    BalanceThirtyPlus = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceThirtyPlus)]),
                    BalanceThirtyPlusCall = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceThirtyPlusCall)]),
                    BalanceSixtyPlus = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceSixtyPlus)]),
                    BalanceSixtyPlusCall = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceSixtyPlusCall)]),
                    Notes = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.Notes)]),
                    BalanceNinetyPlus = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.BalanceNinetyPlus)]),
                    CollectionOneTwentyPlus = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.CollectionOneTwentyPlus)]),
                    CollectionOneTwentyPlusCall = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.CollectionOneTwentyPlusCall)]),
                    Notes2 = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.Notes2)]),
                    Notes3 = Convert.ToString(entity.Properties[nameof(PatientCollectionsModel.Notes3)])
                });
            }

        } while (token != null);

        return pc;
    }

    public async Task<bool> PutPatientCollection(PatientCollectionsModel pc)
    {
        DynamicTableEntity newOne = new DynamicTableEntity { PartitionKey = "current", RowKey = pc.PtId };
        Dictionary<string, EntityProperty> props = new Dictionary<string, EntityProperty>()
        {
            {nameof(PatientCollectionsModel.FirstName), new EntityProperty(pc.FirstName) },
            {nameof(PatientCollectionsModel.PtId), new EntityProperty(pc.PtId) },
            {nameof(PatientCollectionsModel.PatientBalance), new EntityProperty(pc.PatientBalance) },
            {nameof(PatientCollectionsModel.EOB), new EntityProperty(pc.EOB) },
            {nameof(PatientCollectionsModel.PhoneNo), new EntityProperty(pc.PhoneNo) },
            {nameof(PatientCollectionsModel.BalanceCurrent), new EntityProperty(pc.BalanceCurrent) },
            {nameof(PatientCollectionsModel.BalanceThirtyPlus), new EntityProperty(pc.BalanceThirtyPlus) },
            {nameof(PatientCollectionsModel.BalanceThirtyPlusCall), new EntityProperty(pc.BalanceThirtyPlusCall) },
            {nameof(PatientCollectionsModel.DOS), new EntityProperty(pc.DOS) },
            {nameof(PatientCollectionsModel.BalanceSixtyPlus), new EntityProperty(pc.BalanceSixtyPlus) },
            {nameof(PatientCollectionsModel.BalanceSixtyPlusCall), new EntityProperty(pc.BalanceSixtyPlusCall) },
            {nameof(PatientCollectionsModel.Notes), new EntityProperty(pc.Notes) },
            {nameof(PatientCollectionsModel.BalanceNinetyPlus), new EntityProperty(pc.BalanceNinetyPlus) },
            {nameof(PatientCollectionsModel.CollectionOneTwentyPlus), new EntityProperty(pc.CollectionOneTwentyPlus) },
            {nameof(PatientCollectionsModel.CollectionOneTwentyPlusCall), new EntityProperty(pc.CollectionOneTwentyPlusCall) },
            {nameof(PatientCollectionsModel.Notes2), new EntityProperty(pc.Notes2) },
            {nameof(PatientCollectionsModel.Notes3), new EntityProperty(pc.Notes3) }
        };
        newOne.Properties = props;
        newOne.ETag = "*";

        TableOperation updateDenial = TableOperation.Replace(newOne);
        var tableResult = await patientCollectionsTable.ExecuteAsync(updateDenial);

        return tableResult.HttpStatusCode == (int)HttpStatusCode.OK
            || tableResult.HttpStatusCode == (int)HttpStatusCode.NoContent;
    }
[Authorize]
public class GroupHub : Hub
{
    public async Task JoinGroup(string group)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, group);
        await Clients.Group(group).SendAsync("Send", $"{Context.ConnectionId} has joined the group {group}.");
    }

    public async Task LeaveGroup(string group)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
    }

}