当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Asp.Net Web Api2 + SignalR

问题描述:

Help me please!

I have some project of Mail. I need to use SignalR.

Now I only have this in my Startup

app.MapSignalR();

I Have Hub

[HubName("MailHub")]

public class MailHub<THub>: Hub

where THub : IHub

{

public void SendMessage (Mail message)

{

Clients.Caller.addMessage(message);

}

}

I Have MailController

 [Authorize]

[RoutePrefix("api/mail")]

public class MailController : ApiController

{

private readonly MailStore<Mail> _mail;

public MailController()

{

_mail = new MailStore<Mail>(MongoUtil<Mail>.GetDefaultConnectionString());

}

[HttpPost]

[Route("send")]

public async Task<IHttpActionResult> SendMessage(Mail message)

{

var hubContext = GlobalHost.ConnectionManager.GetHubContext<MailHub<IHub>>();

if (hubContext != null)

{

if (!ModelState.IsValid)

return BadRequest(ModelState);

var currentUser = User.Identity.Name;

var sendMessage = new Mail

{

Subject = message.Subject,

Sender = message.Sender,

Receiver = message.Receiver,

Message = message.Message

};

await _mail.CreateAsync(sendMessage);

// hubContext.Clients.Clien....;

/* if (!result.Succeeded)

{

return BadRequest(ModelState);

}

*/

return Ok();

}

return BadRequest();

}

}

And How I Can use SignalR at this Controller?

I need that some user send e-mail to another user using SignalR.

网友答案:

Looking at your code, you can send an email in the same way as you are doing in the controller.

[HubName("MailHub")]
public class MailHub<THub>: Hub
    where THub : IHub
{
    public void SendMessage (Mail message)
    {
        var sendMessage = new Mail
        {
            Subject = message.Subject,
            Sender = message.Sender,
            Receiver = message.Receiver,
            Message = message.Message
        };
        await _mail.CreateAsync(sendMessage);
    }
}

or more simply:

[HubName("MailHub")]
public class MailHub<THub>: Hub
    where THub : IHub
{
    public void SendMessage (Mail message)
    {
        await _mail.CreateAsync(message);
    }
}

There's no inherent requirement for SignalR to send a response back to the SignalR client (unless you wanted to), just receive the parameters and send the mail as you would in the controller.

网友答案:

Hi I change the method to be static and then I was able to call in MVC controler with classname.methodname . I think you can do the same .please try and let me know.

      [HubName("MailHub")]
    public class MailHub<THub>: Hub
          where THub : IHub
    {
    // change to static
    public static void SendMessage (Mail message)
    {
       IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MailHub>();
       context.Clients.All.addMessage(message);
     }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: