Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SE Eventsource Asp.net Core 3.1 #26

Open
Hemalathaerdster opened this issue Sep 28, 2021 · 0 comments
Open

SE Eventsource Asp.net Core 3.1 #26

Hemalathaerdster opened this issue Sep 28, 2021 · 0 comments

Comments

@Hemalathaerdster
Copy link

[ApiController]
[Route("/SSE/[action]")]
public class SSEController : Controller
{
private static ConcurrentBag clients;
static SSEController()
{
clients = new ConcurrentBag();
}
[HttpPost]
public async Task SSECallbackMsg()
{
await CallbackMsg("test");
}
private async Task CallbackMsg(string test)
{
foreach (var client in clients)
{
try
{
var data = string.Format(test);
await client.WriteAsync(data);
await client.FlushAsync();
client.Dispose();
}
catch (Exception)
{
StreamWriter ignore;
clients.TryTake(out ignore);
}
}
}
[HttpGet]
public HttpResponseMessage GETSubscibe()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new PushStreamContent((a, b, c) =>
{ OnStreamAvailable(a, b, c); }, "text/event-stream");
return response;
}

private void OnStreamAvailable(Stream stream, HttpContent content,
    TransportContext context)
{
    var client = new StreamWriter(stream,Encoding.UTF8);
    clients.Add(client);
}

}
Javascript Method of calling above is like

function listenForServerEvents() {
var source = new EventSource('https://localhost:5002/SSE/GETSubscibe');
source.addEventListener("open", function (event) {
console.log('onopen');
}, false);
source.addEventListener("error", function (event) {
if (event.eventPhase == EventSource.CLOSED) {
source.close();
}
}, false);
source.addEventListener("message", function (event) {
console.log('onmessage: ' + event.data);
}, false);
}
when executing, above js function, i am getting error as EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.

Should add anything in startup.cs or is there any mistake., If anyone knows ,kindly help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant