MapHubs not needed in SignalR 1.01? - signalr

I am following the Hubs Quick Start Guide in the Signalr Wiki. I get an error in Global.asax, Application_Start on the line RouteTable.Routes.MapHubs().
A route named 'signalr.hubs' is already in the route collection. Route names must be unique.
Parameter name: name
Maybe this is not needed anymore in 1.0.1? It worked fine in 1.0. It is also mentioned in the readme.txt from NuGet that we need the MapHubs command.
System.ArgumentException was unhandled by user code Message=A route
named 'signalr.hubs' is already in the route collection. Route names
must be unique. Parameter name: name Source=System.Web
ParamName=name StackTrace:
at System.Web.Routing.RouteCollection.Add(String name, RouteBase item)
at System.Web.Routing.RouteCollectionExtensions.Add[T](RouteCollection
routes, String name, T item)
at System.Web.Routing.RouteCollectionExtensions.MapOwinPath(RouteCollection
routes, String name, String pathBase, Action`1 startup)
at System.Web.Routing.SignalRRouteExtensions.MapHubs(RouteCollection
routes, String name, String path, HubConfiguration configuration)
at System.Web.Routing.SignalRRouteExtensions.MapHubs(RouteCollection
routes, String path, HubConfiguration configuration)
at System.Web.Routing.SignalRRouteExtensions.MapHubs(RouteCollection
routes, HubConfiguration configuration)
at System.Web.Routing.SignalRRouteExtensions.MapHubs(RouteCollection
routes)
at SignalrServer.Global.Application_Start(Object sender, EventArgs e) in
C:\RC\Code\Signalr\SignalrServer\SignalrServer\Global.asax.cs:line 18
InnerException:

You need it. Looks like you're calling it twice in your app, don't do that. If you're not explicitly calling it twice then you have and older version of signalr that used to call it for you lying around somewhere in your bin folder. Delete it all and it should work.

Related

.NET Core - How do you reference one IHostedService from another?

I've got two hosted services in my web service: Domain and ComplianceService. ComplianceService needs to reference data and methods in Domain, like so:
public ComplianceService(ILogger<ComplianceService> logger, Domain domain, IRuleRepository ruleRepository)
{
// Initialize the service.
this.logger = logger;
this.domain = domain;
this.ruleRepository = ruleRepository;
}
My initialization in startup.cs looks like this:
// Add the dependencies.
serviceCollection.AddSingleton<RulesActivator>()
.AddSingleton<Accruals>()
.AddSingleton<IRuleRepository, ComplianceRuleRepository>()
.AddSingleton<IViolation, Violation>();
// Add the hosted services.
serviceCollection.AddHostedService<Domain>();
serviceCollection.AddHostedService<ComplianceService>();
When I try to run this, I get this message:
System.InvalidOperationException: 'Unable to resolve service for type 'ThetaRex.OpenBook.ServerDomain.Domain' while attempting to activate 'ThetaRex.OpenBook.WebApi.ComplianceService'.'
If I add Domain to the IoC, like this:
serviceCollection.AddSingleton<Domain>()
.AddSingleton<RulesActivator>()
.AddSingleton<Accruals>()
.AddSingleton<IRuleRepository, ComplianceRuleRepository>()
.AddSingleton<IViolation, Violation>();
It runs, but I get two copies of Domain. I can force it to work like this:
// Add the hosted services.
serviceCollection.AddHostedService(sp => sp.GetRequiredService<Domain>());
if (this.Configuration.GetValue<bool>("ComplianceEnabled"))
{
serviceCollection.AddHostedService<ComplianceService>();
}
But this seems really clumsy and counterintuitive. How come the AddHostedService can instantiate ComplianceService, but can't instantiate the dependent service?

Is there a tool in VS2015 to debug webapi routes?

In Visual Studio 2015 (Enterprise), is there still no built-in tool that will dissect and display the routing information for WebAPI calls?
WebApi Route Debugger does not seem to work for ASP.NET 5 (and mangles the default Help page in the template)
Glimpse does not offer the "Launch Now!" button anymore from what I can tell (http://blog.markvincze.com/use-glimpse-with-asp-net-web-api/).
RouteDebugger is good for figuring out which routes will/will not be hit.
http://nuget.org/packages/routedebugger but you are saying it doesn't work. After some googling I found another solution to your problem,
Add an event handler in Global.asax.cs to pick up the incoming request and then look at the route values in the VS debugger. Override the Init method as follows:
public override void Init()
{
base.Init();
this.AcquireRequestState += showRouteValues;
}
...
protected void showRouteValues(object sender, EventArgs e)
{
var context = HttpContext.Current;
if (context == null)
return;
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
}
Then set a breakpoint in showRouteValues and look at the contents of routeData.
Keep in mind that in a Web Api project, the Http routes are in WebApiConfig.cs ... not RouteConfig.cs
but that's not a tool. may be digging up some thread would help you resolve your issue.
Reference: Is there a way I can debug a route in ASP. MVC5?

Getting error 404 not found with ASP.NET MVC Area routing

I am having a problem with an Area route in MVC 5. When I browse to /Evernote/EvernoteAuth I get a 404 resource cannot be found error.
My area looks like this:
Areas
Evernote
Controllers
EvernoteAuthController
Views
EvernoteAuth
Index.cshtml
The EvernoteAreaRegistration.cs (UPDATE: RegisterArea() wasn't being called so I did a Clean and Rebuild. Now it is called but same result.) contains this route map:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Evernote_default",
"Evernote/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
The EvernoteAuthController's Index() method simply returns View().
My application's RouteConfig.cs currently has no route maps defined, but I tried manually "forcing" it here by implementing this:
routes.MapRoute(
name: "EvernoteAuthorization",
url: "Evernote/{controller}/{action}",
defaults: new { controller = "EvernoteAuth", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "AysncOAuth.Evernote.Simple.SampleMVC.Controllers" }
);
but I get the same results whether this route map exists or is commented out.
Using Phil Haack's asp.net mvc routing debugger I saw that my routes matched fine and the area name, controller name and Action method names matched. I put breakpoints in the controller action methods and those methods were never entered. UPDATE: Those methods were never entered when browsing to /Evernote/EvernoteAuth however when I browsed to just the area name, /Evernote, an EvernoteAuthController was instantiated and the Index() method was called. (Why is that controller being instantiated by /Evernote by not by /Evernote/EvernoteAuth?) Then I received the error:
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/EvernoteAuth/Index.aspx
~/Views/EvernoteAuth/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/EvernoteAuth/Index.cshtml
~/Views/Shared/Index.cshtml
and so on...
In this case I believe ~ = / (application root). So the area Areas\Evernote\Views is not being searched.
How do I troubleshoot this?
It is important tha you add the correct namespace to your controller
namespace YourDefaultNamespace.Areas.Evernote.Controllers
{
public class EvernoteAuthController : Controller
{
...
...
}
}
So the routing can find your controller.
Now you have to register the area in the Global.asax.cs with the method
AreaRegistration.RegisterAllAreas();
Be careful with AreaRegistration.RegisterAllAreas(); inside Application_Start method.
If you put AreaRegistration.RegisterAllAreas() to be last inside Application_Start that will not work.
Put AreaRegistration.RegisterAllAreas() to be first and routing will be successfully executed..
Example:
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas(); //<--- Here work
FilterConfig.Configure(GlobalFilters.Filters);
RouteConfig.Configure(RouteTable.Routes);
AreaRegistration.RegisterAllAreas(); //<--- Here not work
}
Like you found in my post at http://legacy.piranhacms.org/the-magic-of-mvc-routing-with-multiple-areas you probably figured out the all controllers are mapped to the default route (i.e the one you added manually in your route config). If it has been added to the default route, then it will search the location for the default route for its views, i.e ~/Views/...
So the error really seems to be that the Area isn't configured properly. Make sure that you have the following line in your Global.asax.xs:
AreaRegistration.RegisterAllAreas();
This is the line that actually sets up the areas and makes sure that when a controller within a area is hit, the view directory of that area is searched, in your case ~/Areas/Evernote/Views. The thing covered in my blog post was how to eliminate that controllers from your Evernote area are being mapped in the default route.
Hope this help!
Regards
HÃ¥kan
In my case the order of the configuration in Application_Start of global.asax.cs was
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
Changing the order made it work.
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();

A route named "x" is already in the route collection. Route names must be unique. Exception with ASP.NET MVC 3

I'm doing an ASP.NET MVC 3 web service and I keep getting this exception intermittently.
Stack trace:
Server Error in '/' Application.
A route named 'ListTables' is already in the route collection. Route names must be unique.
Parameter name: name
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: A route named 'ListTables' is already in the route collection. Route names must be unique.
Parameter name: name
Source Error:
Line 24: // }
Line 25: // );
Line 26: context.MapRoute(
Line 27: "ListTables",
Line 28: // example:
Source File: C:\inetpub\wwwroot\SchemaBrowserService\Website\Areas\Api\ApiAreaRegistration.cs Line: 26
Stack Trace:
[ArgumentException: A route named 'ListTables' is already in the route collection. Route names must be unique.
Parameter name: name]
System.Web.Routing.RouteCollection.Add(String name, RouteBase item) +2329682
System.Web.Mvc.RouteCollectionExtensions.MapRoute(RouteCollection routes, String name, String url, Object defaults, Object constraints, String[] namespaces) +236
System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults, Object constraints, String[] namespaces) +59
System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults) +17
SchemaBrowserService.Areas.Api.ApiAreaRegistration.RegisterArea(AreaRegistrationContext context) in C:\inetpub\wwwroot\SchemaBrowserService\Website\Areas\Api\ApiAreaRegistration.cs:26
System.Web.Mvc.AreaRegistration.CreateContextAndRegister(RouteCollection routes, Object state) +105
System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state) +199
System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state) +45
System.Web.Mvc.AreaRegistration.RegisterAllAreas() +6
Website.MvcApplication.Application_Start() in C:\Users\djackson\Downloads\RestApiMvc3\Website\Website\Global.asax.cs:35
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
It's probably related to the fact that Route Debugger shows that I have some old routes that I've modified or deleted and won't go away (even after rebooting my machine). The stack trace also refers to a source file that has long since been deleted and my app has been moved to a new location, cleaned and rebuilt since then. What am I missing?
Here is all of my route registration code:
// in Global.asax.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default2", // Route name
"Api/{controller}/{action}/{id}", // URL with parameters
new { controller = "DataSource", action = "Index", area = "Api", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
// in ApiAreaRegistration.cs:
public class ApiAreaRegistration : AreaRegistration
{
public override string AreaName { get { return "Api"; } }
public override void RegisterArea(AreaRegistrationContext context)
{
// DataSources
// Tables
context.MapRoute(
"ListTables",
// example:
// /api/DataSources/DataSource/1/schemata/schema/dbo/tables
"Api/DataSources/DataSource/{dataSourceId}/schemata/{schemaName}/tables",
new
{
controller = "Tables",
action = "TableList",
schemaName = "dbo",
dataSourceId = "DefaultId"
}
);
// Schemata
context.MapRoute(
"Schema",
// example:
// /api/DataSources/DataSource/1/schemata/schema/dbo
"Api/DataSources/DataSource/{dataSourceId}/schemata/{schemaName}",
new
{
controller = "Schema",
action = "Schema",
dataSourceId = "DefaultId",
schemaName = UrlParameter.Optional
}
);
// // DataSources
context.MapRoute(
"SingleDataSource",
"Api/DataSources/DataSource/{dataSourceId}",
new
{
controller = "DataSource",
action = "DataSource",
dataSourceId = UrlParameter.Optional
}
);
context.MapRoute(
"ListDataSources",
"Api/DataSources",
new
{
controller = "DataSource",
action = "DataSourceList",
dataSourceId = "DefaultId"
}
);
context.MapRoute(
"Api_default",
"Api/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
To fix this problem I had to go into the bin folder on my project, delete all DLL files and then rebuild and this fixed the problem.
This error can occur due to multiple causes, I had the same error and solved it by modifying the Global.asax class.
The Application_Start method at Global.asax.cs was like:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
The following line occurs twice in this method:
RouteConfig.RegisterRoutes(RouteTable.Routes);
This ensured that the route was twice added to the route list and at the same time causing the error.
I changed the Application_Start method as follows and the error disappeared:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
This may not be the answer for your problem, but can perhaps help others in the future. I didn't see this answer between the others, so I decided to add this.
I found out that Global.asax was referring to an old version of the site's DLL file before I renamed it. The DLL was not being cleaned up when I did Build > Clean up because the VS project/solution didn't refer to it any more. It seems that sometimes only the newer version of the DLL was being used, allowing the site to work correctly, but eventually both of them would be loaded causing the route conflicts.
The routes get loaded from all assemblies within AppDomain.CurrentDomain, so if your old assemblies are still part of that, you might be still getting old/duplicate routes.
In my case, I faced with this issue, when I added reference to another project from solution, which also was MVC and use the same names in area (I didn't want to added this project, I don't know how it happened). When I removed this DLL, project started to work.
Deleting the DLLs alone didn't work for me (in VS2013), but deleting the entire 'bin' and 'obj' folders and then building the solution worked perfectly! Makes me wish I hadn't spent so long trying to fix it...
None of the suggestions worked for me. Went ahead and restarted the web server (IIS in this case) and that cleared the error after I had fixed the code. DLL must have been cached in IIS.
try this code, only change name
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapHttpRoute(
name: "API",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "GetAgentId" }
);
I am getting same error. But finally I have got solution.
Scenario: I am adding different(mvc4 application) dll in my web api mvc4 application.
When try to run. I am getting same error.
Root Cause- When my web api application run .Application register all area from self and start loading to current application domain dll references. When application load dll(MVC4 application) that time getting error because current maproute already add key for "HelpPage_Default".
Solution.
1.Change key for RegisterArea in maproute either current application or existing application(Refer dll).
2.Move code dll(mvc4 application) code to different liberary and refer to new dll.
I was manually calling AttributeRoutingHttpConfig.Start() in my Global.asax. Did not notice this auto-generated line at the top of the file which automatically calls it.
[assembly: WebActivator.PreApplicationStartMethod(typeof(Mev.Events.Web.AttributeRoutingHttpConfig), "Start")]
I had an application that was a Forms app migrated to MVC with a third party component used for authentication which redirected to another site.
The component would start a session twice if the user wasn't already logged in (once for initial connection to site and once for return).
So I solved this with the following code:
if (routes.Count < 3)
{
routes.IgnoreRoute("login.aspx");
routes.IgnoreRoute("default.aspx");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {action = "Index", id = UrlParameter.Optional}
);
}
Deleting the dlls in the bin folder did work 100%, I still had dlls my project needed to rebuild.
Rather make a copy of the bin folder. then delete the original.rebuild the project. if it fails, place the missing dlls into the bin folder.
I was running an old MVC2 website and I got this issue because the IIS 'Managed Pipeline Mode' was set on 'Integrated' by default (press F4 on the project). Changing it to 'Classic' fixed the issue
When publishing to an Azure App Service I had to check the Publish Dialog's "Settings"->"File Publish Options"->"Remove additional files at destination" to get the old project DLL and symbol files removed. Then the site would load.
This is essentially the current answers (Fleas's) solution at the core. Delete the offending DLL.
What caused this old DLL to be retained was I was loading an older version of the website (MVC 3~5 templates but different web project with colliding namespaces, since the newer version was a copy of this project made some point in the recent past.) The newer project's DLLs just needed to be deleted. There are various ways to achieve this. I found using a dialog to be the easiest atm. Logging into the file system and axing the files by hand certainly works too.
If you are versioning, and you use two APIs with the same name, you will get this error. If you need the same Get, try changing the Name attribute of the route:
TestsController.cs:
[MapToApiVersion("1.0")]
[Route("{moniker}", Name = "GetTest")]
public async Task<IHttpActionResult> Get(string moniker, bool param1 = false)
[MapToApiVersion("1.1")]
[Route("{moniker}", Name = "GetTest11")] // Change name here for a different version
public async Task<IHttpActionResult> Get(string moniker)
And pass in the version in the URL:
http://localhost:6600/api/tests/2020?api-version=1.1
faced this issue. the problem was occurred after adding an area to my project. there was a call for MapMvcAttributeRoutes() in RegisterArea() method. therefore, you should not look for a duplicate route names, just look for duplicate MapMvcAttributeRoutes() calls.

If a ASMX WebService needs a DLL where should it be put?

I'm using some 3rd party software that's failing. Their API is wrapped in a ASP web service.
The call stack tells me that it needs maybe MySQL.Data.DLL or something (not sure exactly) in the correct directory. So I'm wondering where that directory would be. The Web Server is IIS.
Here is the call stack:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
at WebReports.Api.Data.SqlObject.CreateConnectionObject(String dbType, String dataConnStr)
at WebReports.Api.Data.SqlObject..ctor(PageInfo pageInfo, Int32 dataSourceId)
at WebReports.Api.Data.DataObjectBase.GetDataObject(PageInfo pageInfo, Int32 dataSourceId, String objectType, Boolean isSqlSpecific)
at WebReports.Api.Reports.Entity.get_DataSource()
at WebReports.Api.Reports.Entity.GetColumnProcess(String colName, Boolean isActual)
at WebReports.Api.Reports.EntityColumnsCollection.GetColumnProcess(String colNameFull, Boolean isActual)
at WebReports.Api.Common.PageInfo.GetMnemonicFromId(String id)
at WebReports.Api.Reports.KeyColumnCollection.SetColumnMnemonics()
at WebReports.Api.Reports.ReportEntityCollection.SetColumnMnemonics()
at WebReports.Api.Reports.ReportEntityCollection.LoadData(DataSet ds, Boolean readSchema)
at WebReports.Api.Reports.Report.get_Entities()
at WebReports.Api.Common.PageInfo.GetMnemonicFromId(String id)
at WebReports.Api.Reports.Cell.set_SaveText(String value)
at WebReports.Api.Reports.ReportCellCollection.LoadData(DataSet ds)
at WebReports.Api.Reports.Report.get_Cells()
at WebReports.Api.Reports.Report.UpdateVersion()
at WebReports.Api.Reports.Report.Validate(Boolean validateJoins)
at WebReports.Api.Reports.Report.LoadData(Boolean validate)
at WebReports.Api.Reports.Report.Load(String reportName)
Above this line is their API, so I can't inspect it:
at eWebReportsLETG.ReportURLService.GenerateReportURL(Int32[] list, String m_szWebReportsVirtualDirectory, String m_szWebReportsUrl, String ReportDir, String ReportName, String PkSpecialName, Boolean& Failed) in C:\dev\eWebReports\eWebReportsLETG\ReportURLService.asmx.cs:line 51
I needed to copy MySQL.data.dll to the bin directory of my web service application directory. I also added the config key to the web.config.

Resources