I am using Visual Studio 2019 and implementing SignalR 5.0.0.0 in MVC project of .NET 5 framework. but unfortunately, I always get the connection error. can you please help me out? BTW it works for .net 5 with SignalR version 3.1.0.
SignalR version snippet:
SignalR conneciton script is as follows:
var connection = new signalR.HubConnectionBuilder().withUrl("/pushNotificationHub").build();
connection.on("Recive", function (notification) {
$("#modal-title").text(notification.title);
$("#modal-content").text(notification.content);
$('#myModal').modal('show');
});
connection.on("Connect", function (connectionId) {
$("#CallerConnectionId").val(connectionId);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
Below is the browser error
Related
I have tried this code to generate the token:
public async Task Authenticate() {
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(_clientId), "client_id");
content.Add(new StringContent(_clientSecret), "client_secret");
content.Add(new StringContent("client_credentials"), "grant_type");
content.Add(new StringContent(".default"), "scope");
try {
var task = _client.PostAsync(new Uri(string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", _tenantId)), content);
var res = task.GetAwaiter().GetResult();
if (res.StatusCode == System.Net.HttpStatusCode.OK) {
JsonDocument resJSON = await JsonDocument.ParseAsync(await res.Content.ReadAsStreamAsync());
_accessToken = resJSON.RootElement.GetProperty("access_token").GetString();
lock(this) {
_expiresAt = DateTime.UtcNow.AddSeconds(resJSON.RootElement.GetProperty("expires_in").GetInt16());
}
} else
throw new Exception(res.ReasonPhrase);
} catch (WebException ex) {
// handle web exception
}
}
But I got the error like
error_description=AADSTS1002016: You are using TLS version 1.0, 1.1 and/or 3DES cipher which are deprecated to improve the security posture of Azure AD. Your TenantID is: 334xxxx. Please refer to https://go.microsoft.com/fwlink/?linkid=2161187 and conduct needed actions to remediate the issue. For further questions, please contact your administrator.
Trace ID: c8a502xxxx
Correlation ID: 325a1dxxxxx
Timestamp: 2022-08-04 13:35:23Z
But the same code works in console application.While using this code inside the dll it throws the exception.All the versions are same - .net framework,System.text.json,system.memory etc.
Please help me to sort out this.
According to this page the default TLS version that is used, depends on the targeted .net version and the used operating system.
Targeting .net framework 4.8 should default to TLS1.2 on Windows 10/11
Any change that you are using an older version of either? Or that you are setting the tls version explicitly somewhere in your application?
Also using lock inside an asynchronous method is bad practice and might deadlock your code.
When I use .NET Framework 4.6.1, I encounter the same problem. After I switched the version to 4.7.2, the problem was not solved until I explicitly specified the version in Web.config.
<httpRuntime targetFramework="4.7.2" />
I am developing a application using .Net core 3.1 and Angular 8. Every thing is fine with the application except one API call. The API call is of type GET and only that API call is getting stalled. I am not able to find the reason for it as I am calling and utilizing it same as other APIs. And other APIs are working perfectly fine. I have searched for the issue and found that Google Chrome doesn't support more than 6 TCP connections at a time.
I have run the command netstat -aand got this which I am not able to understand
Below is Angular Code :
getAllTrainings(){
this.apiService.get(environment.master_api_url, 'Training/GetAllTrainingDetails')
.subscribe(result => {
if (result) {
this.allTrainings = result;
this.dataSource = new MatTableDataSource<any>(this.allTrainings)
console.log(result, 'getAllTraining');
}
},error=>{
console.log(error, 'error while fetching all trainings')
})
}
Below is .Net Core Code :
[HttpGet("GetAllTrainingDetails")]
public async Task<IActionResult> GetAllTrainings() {
var trainingDetails = await _trainingService.GetAllAsync();
return Ok(_mapper.Map<List<AllTrainingsDto>>(trainingDetails));
}
While debugging I found the issue:
public async Task<List<TrainingDetail>> GetAllAsync() {
return await _dbSet
.Include(x=> x.ParticipantDetail)
.Include(x=> x.Trainer)
.Include(x=> x.Program)
.Include(x => x.ParticipantDetail)
.ThenInclude(x => x.Participant)
.ToListAsync();
}
Does any one find something wrong with code which can be the reason for this specific API call getting stalled.
I have an ASP .NET web application using SignalR 3.0 in ASP .NET Core 3.1 with a C# client. When I run the application in Visual Studio, the client can connect to signalR just fine. However, when I deploy the application on IIS and update the client-side URL, I get a 404 error. I have verified that I can hit the endpoint from the browser and I get a "connection id required" message. Has anybody else encountered this?
Client code:
HubConnection hubConnection = new HubConnectionBuilder().WithUrl(hubAddress).WithAutomaticReconnect().Build();
try
{
await hubConnection.StartAsync();
}
catch (HttpRequestException e)
{
// this is where the 404 exception occurs.
}
Server-side mapping code in startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<MyHub>("/myHub");
});
I'm getting a 'TypeError: Failed to fetch' error when trying to call my AspNetCore Restful API from Blazor Wasm. I can call it from Postman, and it works fine.
My Environment:
Microsoft Visual Studio Community 2019 Preview Version 16.6.0 Preview 3.0
Client: Blazor Wasm Service (dotnetstandard 2.1)
AspNet.WebApi.Client 5.2.7
AspNetCore..WebAssembly 3.2 preview 4.2
System.Net.Http.Json 3.2 preview 5.2
Important Usings:
using Microsoft.AspNetCore.JsonPatch;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
Parent namespace and class omitted
_httpClient is injected into parent class
public async Task<MyDto> UpdatePartialAsync(Guid primaryId, ObjectForUpdateDto objectForUpdateDto)
{
MyDto dtoFromApi = null;
var patchDoc = new JsonPatchDocument<ObjectForUpdateDto>()
.Replace(o => o.Name, objectForUpdateDto.Name)
.Replace(o => o.Description, objectForUpdateDto.Description)
var uri = $"MyUri/myResources/{primaryId}";
try
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var serializedPatchDoc = JsonConvert.SerializeObject(patchDoc);
var json = new StringContent(serializedPatchDoc, Encoding.UTF8, "application/json-patch+json");
var response = await _httpClient.PatchAsync(uri, json);
return await response.Content.ReadAsAsync<MyDto>();
}
catch (Exception)
{
throw; //throws 'TypeError: Failed to fetch'
}
return dtoFromApi;
}
My API (.Net 5.0, also tried .Net Core 3.1):
[HttpPatch]
[Route("{primaryId}")]
public ActionResult UpsertPartial([FromRoute]Guid primaryId, [FromBody] JsonPatchDocument<ObjectForUpdateDto> objectForUpdateDto)
{
//client call never makes it here
return NoContent();
}
What a misleading error message. It was a CORS issue.
The fix was adding "PATCH" to my CORS policy in my API's startup.cs ConfigureServices method (which previously was "GET, DELETE, PUT, POST, OPTIONS").
services.AddCors(options =>
{
options.AddPolicy(CorsAllowAll,
builder =>
{
builder.WithOrigins(Constants.ApiClientCors).AllowAnyHeader().WithMethods("GET, PATCH, DELETE, PUT, POST, OPTIONS");
});
});
#inliner49er, I wish that I could add a comment to clarify what you responded, since your answer is correct, but I don't have enough reputation points. Therefore, I'll post my tweaks to your answer as a separate answer.
You nailed it, the CORS issue fixed my program also. The only part of your code that didn't make sense was the reference that you have to a class called Constants. I am in the process of trying to complete the PluralSight tutorial, and because I'm working entirely internally, I can safely replace your code with the following:
services.AddCors(options =>
{
options.AddPolicy("PolicyName", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
I am super new to all of this, literally hours into the process of learning about it, so there is a buttload that I don't understand. I just thought I'd post this to help anyone who might have similar questions to what I had.
You can also try adding these lines directly to the Configure method of the Startup class:
//ENABLE CORS
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials
I have an ASP.NET Core web API with a SignalR Hub and a .NET Core console app that acts as a client for the hub.
The console app throws the following error when trying to connect:
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred. (StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Date: Mon, 20 May 2019 18:12:44 GMT
Server: Kestrel
Content-Length: 0
})
Source=System.Private.CoreLib
StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at SurveyApp.NotificationClient.Program.Main(String[] args) in C:\Users\user\source\repos\SurveyApp\SurveyApp.NotificationClient\Program.cs:line 16
Inner Exception 1:
HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Date: Mon, 20 May 2019 18:12:44 GMT
Server: Kestrel
Content-Length: 0
}
I have tried all kinds of renaming of routes and hubs, but it still doesn't work. Also tried the solution shown here since it is a similar issue, but still not result: HttpClientException when connecting to working hub from SignalR .NET Client
Server:
DI registration:
services.AddSignalR();
Middleware registration:
...
app.UseSignalR(route =>
{
route.MapHub<NotificationHub>("/notificationhub");
});
app.UseMvc();
Hub class:
public class NotificationHub : Hub
{
public Task SendMessage(string message)
{
return Clients.All.SendAsync(message);
}
public override Task OnConnectedAsync()
{
Console.WriteLine("A client connected");
return base.OnConnectedAsync();
}
}
Client code:
static void Main(string[] args)
{
var connection = new HubConnection("https://localhost:5001/notificationhub");
connection
.CreateHubProxy("NotificationHub")
.On<string>("ReceiveNotification", Console.WriteLine);
connection.Start().Wait();
Console.WriteLine("Connection started");
Console.ReadKey();
}
When I don't call Wait() after connection.Start(), I do not get any error, but the client still doesn't connect. I'm running .NET Core 2.2 both on the server and the client and the version for the SignalR nuget is 2.4.1
var connection = new HubConnection("https://localhost:5001/notificationhub");
This construction doesn't exist in ASP.NET Core any more. Seems that you're connecting an ASP.NET Core SignalR server with a Microsoft.AspNet.SignalR.Client, which should work with ASP.NET SignalR and is not compatible with ASP.NET Core.
If that's the case, you need add a reference to Microsoft.AspNetCore.SignalR.Client which targets .NETStandard 2.0 and should be able to run on .NET Framework too.
And then create a connection as below :
var Connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/notificationhub")
.ConfigureLogging(logging =>{
logging.AddConsole();
})
.Build();
For more details, see https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2#connect-to-a-hub