I can get this tutorial to work in a new project, but not in my existing project.
My project is an ASP.Net MVC 4 web application with the following attribute in the web.config file:
<appSettings>
<add key="webpages:Enabled" value="true"/>
</appSettings>
This is because my application is a Single-Page-Application, which uses AngularJS on the client side. The only page in my application is index.cshtml, to which I've added the relevant code for signalR:
<!-- signalR chat -->
<script src="~/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
Then I've got the ChatHub.cs file:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
And finally in the global.asax:
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
When I run the application, the /signalr/hubs file is not generated. I get a 404 when requesting the file, and it crashes on the line:
chat.client.broadcastMessage = function (name, message) { ....
because chat is null as the previous line did not find chatHub:
var chat = $.connection.chatHub;
Does anyone know what's wrong with my code ?
UPDATE
I have solved my problem by changing the line::
<script src="/signalr/hubs"></script>
to
<script src="~/signalr/hubs"></script>
I have solved my problem by changing the line::
<script src="/signalr/hubs"></script>
to
<script src="~/signalr/hubs"></script>
Also, the reason why /signalr/hubs are not generated is forget to Map SignalR in OWIN Startup Configuration.
public class Startup
{
public void Configuration(IAppBuilder appBuilder){
...
appBuilder.MapSignalR();
...
}
...
In my case, it was because my ChatHub class was not marked public.
I had a similar problem where the hubs file wasn't being generated. It looks like the OP was following the steps here. The way I fixed the problem had to do with the jquery includes. The tutorial I linked below was written with jquery 1.6.4 and jquery-signalr version 2.1.0. When Visual Studio generated the Scripts folder for me, it used jquery version 1.10.2 and jquery-signalr version 2.0.2.
The way I fixed this was simply to edit the index.html file. Note that you can use Chrome's javascript console window Ctrl+Shift+J to see errors.
For me the solution was to reinstall all the packages and restore all the dependecies.
Open nuget powershell console and use this command.
Update-Package -Reinstall
I'll like to add that the signalR Readme file have some note about this issue.
And also if your signalR page is in a PartialView some script should be place in the master page.
Please see http://go.microsoft.com/fwlink/?LinkId=272764 for more information on using SignalR.
Upgrading from 1.x to 2.0
-------------------------
Please see http://go.microsoft.com/fwlink/?LinkId=320578 for more information on how to
upgrade your SignalR 1.x application to 2.0.
Mapping the Hubs connection
----------------------------
To enable SignalR in your application, create a class called Startup with the following:
using Microsoft.Owin;
using Owin;
using MyWebApplication;
namespace MyWebApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Getting Started
---------------
See http://www.asp.net/signalr/overview/getting-started for more information on how to get started.
Why does ~/signalr/hubs return 404 or Why do I get a JavaScript error: 'myhub is undefined'?
--------------------------------------------------------------------------------------------
This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.
Please make sure that the Hub route is registered before any other routes in your application.
In ASP.NET MVC 4 you can do the following:
<script src="~/signalr/hubs"></script>
If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:
<script src="#Url.Content("~/signalr/hubs")"></script>
If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager
using a app root relative path (starting with a '~/'):
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
If the above still doesn't work, you may have an issue with routing and extensionless URLs. To fix this, ensure you have the latest
patches installed for IIS and ASP.NET.
In my case i was missing :
app.MapSignalR();
in public void Configuration(IAppBuilder app) function located in startup.cs
Some advice for those that start scaling out from the get go. In my case I was working on getting a remote client to work and never realized that
A. the tutorial example lists the web app(server) startup in a using statement, after which the web app disposes properly and no long exists.
I got rid of the using statement and keep a reference to the web app
for later disposal
B. the client has a different url than the server. the example relies on them having the same url. the "/signalr/hubs" is an endpoint run by the signalr server, called by the signalr client to get a script of all the hubs the server implements.
You need to include "http://myServerURL/signalr/hubs", rather than making it
relative to the client.
No lies. This tripped me up for a solid 2 weeks, because by some magic the solution worked anyways on my coworker's setup. This caused me to keep looking for IIS settings and firewall settings and CORS settings that must have been blocking the connection on my computer. I scavenged every last stack overflow question I could and the ultimate answer was that I should have just implemented a heartbeat monitor on the web app from the start.
Good luck and hopefully this saves other people some time.
See if Microsoft.Owin.Host.Systemweb nuget package is not installed, and therefore not building the dynamic js lib.
OwinStartup not firing
Related
I'm working on a simple .NET 6 application to enable data update notifications in our front-end application. I've built something similar in .NET 5 before, but I'm running across a DI issue that's got me stumped. In 5, all hubs that were mapped automatically have an IHubContext that is set up in the container for them as well. That doesn't appear to be the case anymore in 6.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]' while attempting to activate 'SignalRNotifications.Controllers.NotificationController'.
The new non-startup DI in 6 looks weird to me, but I'm just not seeing anything available that says how to fix it. Any suggestions on how to get an IHubContext to inject into my controller?
Thanks!
Update: Here is some pertinent code:
using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/NotificationHub");
});
app.Run();
Dependency injection is done in the controller in the most predictable of ways:
namespace SignalRNotifications.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly IHubContext<NotificationHub> _notificationContext;
public NotificationController(IHubContext<NotificationHub> notificationContext)
{
_notificationContext = notificationContext;
}
System.InvalidOperationException: Unable to resolve service for type
'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]'
while attempting to activate
'SignalRNotifications.Controllers.NotificationController'.
The issue might be related to you having installed the wrong version of SignalR and adding the wrong namespace reference. You are using Microsoft.AspNet.SignalR.IHubContext, instead of Microsoft.AspNetCore.SignalR.IHubContext.
According to your code and refer to the Asp.net Core SignalR document, I create a sample and inject an instance of IHubContext in a controller, everything works well. But I notice that when using the IHubContext, we need to add the using Microsoft.AspNetCore.SignalR; namespace, like this:
So, please check your code and try to use:
using Microsoft.AspNetCore.SignalR;
During development, i have used Swagger on the server side of my Blazor WebAssembly App. Always launching (debug) using kestrel instead of IIS Express.
Routing worked as expected, all my component routed properly and if i manually typed /swagger, i got to the swagger page. All good.
We have deployed under IIS on our pre-prod servers, the Server side and Blazor WebAssembly App (client) work as expected and are usable, however, my /swagger url gets rewritten (I assume) to go somewhere in my App instead of letting it go to Swagger, obviously there isn't any component that answers to /swagger.
My only guess is that, when hosted on IIS, the aspnet core app takes care of telling IIS what to rewrite and how (similar to the configs that could be provided thru a web.config for a "Standalone" deployment.)
I can't find how to specify exceptions, I've been following the doc at
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/webassembly?view=aspnetcore-3.1#iis
Any idea how i could add an exception for /swagger ?
EDIT:
Turns out it works without issues in Chrome, only Firefox has the unwanted behavior. If i clear my cache, or use Incognito mode, the issue does not happen in Firefox. So, it seems that Firefox caches some stuff and tries to send my URL input to the Blazor Wasm instead of going thru to the server. I will debug some more with the dev tools and fiddler open to try and figure it out, will report back.
Turns out there this is part of the service-worker.js file that is published. It is different in dev than what gets published (which makes sense).
During my debugging i was able to reproduce the issue on all browsers (Edge, Chrome and Firefox), regardless of being in Incognito/Private mode or not.
Once the service-worker is running, it handles serving requests from cache/index.html of the Blazor WebAssembly app.
If you go into your Blazor WebAssembly Client "wwwroot" folder, you'll find a service-worker.js and a service-worker.published.js. In the service-worker.published.js, you will find a function that looks like this :
async function onFetch(event) {
let cachedResponse = null;
if (event.request.method === 'GET') {
// For all navigation requests, try to serve index.html from cache
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
const shouldServeIndexHtml = event.request.mode === 'navigate'
&& !event.request.url.includes('/connect/')
&& !event.request.url.includes('/Identity/');
const request = shouldServeIndexHtml ? 'index.html' : event.request;
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
}
return cachedResponse || fetch(event.request);
}
Simply following the instructions found in the code comments is gonna fix the issue. So we ended up adding an exclusion for "/swagger" like so :
&& !event.request.url.includes('/swagger')
Hopefully this post is useful for people who are gonna want to serve things outside of the service worker, not only Swagger.
Do you have UseSwagger first in your Startup.Configure method?
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "YourAppName V1")
);
In Startup.ConfigureServices I have the Swagger code last.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
c.SwaggerDoc(
name: "v1",
info: new OpenApiInfo
{
Title = "YourAppName",
Version = "V1",
}));
}
This is working just fine for us.
Note: You must navigate to https://yourdomain/swagger/index.html
Summary:
I have a .NET Core project that uses the React web app template for the front end. This app uses Entity Framework Core to connect to an Azure SQL Database. I used the Db-Scaffold command to generate my models (just one table at the moment), and created a controller to return this table. Locally, this works fine and the table (JSON) is returned at localhost/api/Users. However when I deploy the website to Azure (CD pipeline is VS 2017 - > GitHub -> DockerHub -> Azure Web App), navigating to mysite.azurewebsites.net/api/Users just renders the login page (React) of my app.
Attempts:
I have tried:
Adding a connection string as a shared value in Azure (named DefaultConnection)
Adding all the outbound IP's of the Azure Web App to the Azure SQL Whitelist
Running the following in the consoles of the web app
fetch('api/users')
This just returns:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I have also tried changing database values and refreshing the local version to make sure it was not just a cached page and sure enough the changes were reflected locally.
I also set ASPNETCORE_ENVIRONMENT in the Web App settings in Azure to Production. Although when I go to the error message, page (through the console) I get this:
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<p>
<strong>Request ID:</strong> <code>0HLK3RLI8HD9Q:00000001</code>
</p>
<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Code
UsersController.cs
[Route("api/[controller]")]
public class UsersController : Controller
{
private readonly AccrubalanceDbContext _context;
public UsersController(AccrubalanceDbContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public async Task<IEnumerable<Users>> Get()
{
return await _context.Users.ToListAsync();
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection":<MyConnectionStringGoesHere>
},
index.js (just in case React might be the routing problem)
const baseUrl = document.getElementsByTagName('base')
[0].getAttribute('href');
const rootElement = document.getElementById('root');
ReactDOM.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>,
rootElement);
registerServiceWorker();
Startup.cs (could be potentially problem with HTTP routing in Prod?)
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddDbContext<AccrubalanceDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
Conclusion
In conclusion, I need this API call to work within the hosted Azure Web App like it does on my local machine. I know I am close since I got it to work locally, but I am missing something along the way to Azure. Any help or pointers you can provide would be great :)
I am still new to SO and took my time to do my best to format this correctly. I am open to constructive formatting critiques and suggestions to help me improve.
Edit:
As I mentioned before, I am using docker for CD/CI. So I ran my docker container locally and the api does not work there either. Docker throws this warning in the command window when I navigate to the apps home page.
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
Edit 1 Determination
I also found this article which points to react routing being an issue. I have looked in Kudo in my Azure app and I do not have a web.config. Could potentially try adding on but I do not have the regular Windows UI since my app is a Linux server.
The container build acts like the Azure App does, may not be an Azure issue. Still unsure why docker is acting differently than running in VS.
Solution:
There is obviously some problem with Docker. Since it was becoming more of a headache then a help, I removed it from the deployment pipeline and just followed the instructions here. Once I did this deployment method, all the API's worked. Only downside is I had to make a new app in Azure.
I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.
My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.
In Package Console Manager run:
Install-Package Swashbuckle
To get your Test Web API controller working:
1) Comment this out in the WebApi.config:
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Now this URL:
http://localhost:33515/api/Test
brings back XML:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
In Global.asax Register() I call:
SwaggerConfig.Register();
In AppStart.Swagger.Config Register() I put:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1.0", "HRSA CHAFS");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{});
}
private static string GetXmlCommentsPath()
{
var path = String.Format(#"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."
I've been stuck on this for hours.
How do you get rid of this?
This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.
Delete your bin folder and re-build your solution.
This resolves the swagger error.
Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
in my case i added another project as refrence and that other project has swagger too.
i remove that refrence and move needed code to new project.
I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:
A route named 'DefaultApi' is already in the route collection error
In my experience the error occurs when you add reference to another project and that project is a service and it occurs on the SwaggerConfig of the referenced project. Removing project reference usually solve the problem, if you need to share classes I suggest you to create a specific project as Class Library and add its reference to both your services
I've scoured the site, coming across SignalR OnConnected and OnDisconnected not firing and similar, but the solution does not apply in my case. I already do have the client methods registered.
Additionally, the OnConnected method of my hub does fire when running on my local box. It simply does not fire when deployed. All other methods work fine, however. For the present, I've created a work-around as such:
<script>
$(function () {
var myHub = $.connection.myHub;
myHub.client.clientMessage = function (message) { alert(message); };
// Start the connection.
$.connection.hub.start().done(function () {
myHub.server.superfluousMethodToDoSameThingInOnConnect();
});
});
</script>
I would really like to stop using this second call, however, and simply have OnConnected work properly as it should. What is necessary on my deployment server to have it work the same?
For reference, my SignalR is version 1.2.2 (limited to .NET 4.0, for now) incorporated into an MVC site (with no errors, otherwise).
My dev box is Windows 7 hosting in IIS Express 8.5
The deployment box is Winows Server 2003 hosting in IIS V6.0.
Edit 1: I've included a
myHub.connection.stateChanged(function (change) { alert("State: " + change.newState); });
for debugging, and when the page loads, it displays popup of "State: 0" followed by a popup of "State: 1" a short time later, and a "State: 4" when I leave the page, so it looks like my connection itself is behaving correctly. This functions the same both locally and on the deploy server.
Edit 2: To test further, I have updated the methods in the hub as below:
public override Task OnConnected()
{
Groups.Add(Context.ConnectionId, Context.User.Identity.Name);
Clients.All.clientMessage("OnConnected:: ID: " + Context.ConnectionId + " USER: " + Context.User.Identity.Name);
return base.OnConnected();
}
public void SuperfluousMethodToDoSameThingInOnConnect()
{
Clients.All.clientMessage("SuperfluousMethodToDoSameThingInOnConnect:: ID: " + Context.ConnectionId + " USER: " + Context.User.Identity.Name);
}
Results of this testing show that only the text sent from SuperfluousMethodToDoSameThingInOnConnect is shown back to the Caller. However, other clients (tested in other browser windows) see both the text from OnConnected and SuperfluousMethodToDoSameThingInOnConnect.
Additionally, when I try to send a message back to the caller using Context.Groups(Context.User.Identity.Name) then the message is not sent. However, if I move the group registration line Groups.Add(Context.ConnectionId, Context.User.Identity.Name) from OnConnected into SuperfluousMethodToDoSameThingInOnConnect, then messages can be sent using Groups.Add(Context.ConnectionId, Context.User.Identity.Name). This seems extremely bizarre, as I can see that the OnConnected method is called, but the Group is not really registered?
Really at a loss for anything to explain this erratic behavior.
Edit 3: Pushed the web app out to a Windows Server 2012 VM, where I found it works correctly, same as my local dev box. Is it that SignalR does not fully work on IIS 6?
As per 'Supported server IIS versions' in the http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/supported-platforms only IIS7 or newer are supported.