i try to connect my signalr hub with flutter client after connection.start then i try to invoke method its give error that 'Invocation canceled due to the underlying connection being closed'.
i tried to run it on different iis server same result occurs. can somebody guide me
Flutter Client code is here
Future<void> signalr() async {
const serverUrl = "<serverurl>";
// Creates the connection by using the HubConnectionBuilder.
final hubConnection = HubConnectionBuilder().withUrl(serverUrl).build();
// When the connection is closed, print out a message to the console.
// final hubConnection.onclose( (error) => print("Connection Closed"));
hubConnection.serverTimeoutInMilliseconds = 1000000;
await hubConnection.start();
hubConnection.onclose(({error}) {
});
final result = await hubConnection.invoke("joinRoom", args: ['1']);
print('Result: $result');
hubConnection.on('RecieveMessage', (message) {
print('sasta123'+ message.toString());
});
}
startup.cs is here
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v2", new OpenApiInfo
{
Version = "v2",
Title = "AM_ChatAPI",
Description = "AM_ChatAPI-v2",
TermsOfService = new Uri("https://www.adamjeelife.com"),
Contact = new OpenApiContact
{
Name = "AdamjeeLife",
Email = string.Empty,
Url = new Uri(""),
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri(""),
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
c.ResolveConflictingActions(apiDesc => apiDesc.First());
});
//Step2
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,//if False then that the expired token is considered valid
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))//key must be min 16 chars
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = c =>
{
if (c.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
c.Response.StatusCode = 401;
c.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject(new string("Token Expired"));
return c.Response.WriteAsync(result);
}
else
{
return Task.CompletedTask;
}
},
};
});
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(5);
}).AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseFileServer();
app.UseStaticFiles();
// loggerFactory.AddSerilog();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v2/swagger.json", "CoreApp APIv2");
});
app.UseHttpsRedirection();
app.UseRouting();
//app.UseRouting();
//global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
});
}
}
```
