Signalr in Asp.Net MVC 4 app - asp.net-mvc

I'm working on Asp.net MVC app, I'd like to use signalr.
Signalr to be hosted in IIS.
I added the signalr dlls and added the reference to it.
In Global.asax,
I put the code,
inside Application_Start()
" RouteTable.Routes.MapHubs();"
I've pasted the Global.asax,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
RouteTable.Routes.MapHubs();
}
}
When i run the app, say, "http://localhost:4432",
When I try "http://localhost:4432/signalr/hubs", I get exception as follows,
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /signalr/hubs
Signalr version : I tried with V1.1.25 and 2.0
Someone direct me what I should do to get it corrected?

1.write a hub extends Hub
public class MessageHub : Hub
2.check web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">

I tried,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
Put "RouteTable.Routes.MapHubs();" in the first line of Application_Start() method.

Related

WebAPI ActionName not routing after publish: 404 - File or directory not found

When testing my action in VS, everything is working fine.
After deploying, /site/controller responds as expected (403) while /site/controller/action responds with a 404.
Other api projects deployed from the same solution to the same root are working as expected.
Each project is configured as an application in IIS.
Can you give me a clue on how to proceed or what information to add here that would clarify the configuration?
Global.asax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
namespace ssa
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
}
}
}
WebApiConfig.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ssa
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Iam not sure if you need to register all routes in your global.asax, but check this:
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs
Check is your server configured to run targeted .net version it may be some differences between web api 1.0 and 2.0 at the server point of view.

Adding new controller gives HTTP error

In my ASP.NET MVC 5 application, I used to have a controller called Alpha, which I played around with for a while, and then ended up deleting it. Now, I've decided that I want to have another controller called Alpha, with different functionality from before.
So, I have added a new controller, named it Alpha, and added an Index view for this controller. But when I go to localhost:IP/Alpha, I get the following error:
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
All I have done though, is add the controller with the code, and then add an Index view with the default code.
The strange thing, is that if I add a controller and a view in the same way, but call it anything other than Alpha, then the application works as would be expected, and Alpha's Index view is displayed.
So I am assuming there is something remaining in the system from the old Alpha controller (which may have originally been buggy, I cannot remember), which is conflicting with this new Alpha. Any ideas on how I might investigate this further?
As requested by Jason Evans, here is my Global.asax.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Poseidon
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
As requested by Jason Evans, here is my RoutConfig::RegisterRoutes function:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Web API Attribute Routes in MVC 5 exception: The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized()

On an MVC 5 with Web API I have the following, using only Attribute Routes:
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); // TODO: Check for Apple Icons
RouteTable.Routes.MapMvcAttributeRoutes();
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
AreaRegistration.RegisterAllAreas();
In the RouteTable all the MVC routes were created ... But not the API ones ...
I checked the RouteTable.Routes and I see an exception:
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at
System.Web.Http.Routing.RouteCollectionRoute.GetEnumerator() at
System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
For testing this I added only two Web Api actions to the project:
[RoutePrefix("api")]
public class StatApiController : ApiController {
[Route("stats/notescreateddaily"), HttpGet]
public IHttpActionResult NotesCreatedDaily() {
// Some code
}
[Route("stats/userscreateddaily"), HttpGet]
public IHttpActionResult UsersCreatedDaily() {
// Some code
}
}
Am I missing something?
Thank You,
Miguel
The solution is in fact replacing:
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
By:
GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
That was a change in Web API 2.
The solution is to call GlobalConfiguration.Configuration.EnsureInitialized(); after all your Web API related configuration is done, but I am curious as to why your registrations look like this...What kind of project template did you use to create the MVC5 project?...The predefined templates that come with Visual Studio has a structure which helps minimize route ordering problems and so would recommend using them, so wondering why your configuration structure looks like that...
I am having the same problem after I upgrade all my web services project using ASP.Net Web API 4.0 to 4.5 and using Web API 2.2 with Cors library. I managed to successfully solve the problem. What I did was eliminating or commenting out the following statement at the RouteConfig.cs file at App_Start folder:`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace myNameSpace.Configurations
{
public static class RouteConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
//DON'T USE THIS. IT WILL GIVE PROBLEMS IN INSTANTIATION OF OBJECTS
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LocationData",
routeTemplate: "dataservices/locations/{controller}/{action}/{id}",
defaults: new {action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ProfileData",
routeTemplate: "dataservices/profiles/{controller}/{action}/{id}",
defaults: new { action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
On my Global.asax.cs file I am using the old routing registration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net.Http.Formatting;
using myNameSpace.IoC;
using myNameSpace.Configurations; // Here actually I change the protected void Application_Start() to protected void Configuration() and change the folder to configuration instead on App_Start
using myNameSpace.Controllers.ExceptionSchema;
using myNameSpace.Filters.HttpFilters;
namespace myNameSpace
{
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterApis(HttpConfiguration config)
{
config.Filters.Add(new CustomHttpExceptionFilter());
}
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
RegisterApis(GlobalConfiguration.Configuration);
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.Register(GlobalConfiguration.Configuration);
}
}
}
Here is the reason:
Attribute Routing in Web API 2
Note: Migrating From Web API 1
Prior to Web API 2, the Web API project templates generated code like this:
protected void Application_Start()
{
// WARNING - Not compatible with attribute routing.
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
If attribute routing is enabled, this code will throw an exception. If you upgrade an existing Web API project to use attribute routing, make sure to update this configuration code to the following:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}
I am using the old route and I decided not to use attribute routing. So take OUT THAT statement

Parser error in ASP.net mvc

I am following the tutorial from this site here. Everything was going fine until I added the css and image folder. after adding these two things and running my project, I got the following error:
. I have two controller classes and one view class. If you guys want, I can share them with you. But if you also click on the link I provided, you can see the code there as well. Thanks for your time and help.
Here's my global.asax file:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcMovieStore
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
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();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(#"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
check the code-behind file, global.asax.cs, the namespace should be MvcMovieStore, and the class name should be MvcApplication, I guess the class name doesn't match.
THis is wiered but I did not do anything, I simply ran it again and it worked. Amazing.
I got the same error for no particular reason. Simply close and re-open Visual Studio has fixed my problem.
I found that changing the Namespace on the project, without refactoring that across the whole solution was my problem. Check your project Properties and see what your namespace is, ensure that lines up, across the board.

ASP.NET MVC 2, Ninject 2.2 and no parameterless constructor defined for this object

So I've been spending some time with ASP.NET MVC 2 (currently stuck with using Visual Studio 2008) and have now moved onto using Ninject 2.2 and its MVC integration. I've downloaded Ninject 2.2 and Ninject.Web.Mvc from the following locations:
https://github.com/downloads/ninject/ninject/Ninject-2.2.0.0-release-net-3.5.zip
https://github.com/downloads/ninject/ninject.web.mvc/Ninject.Web.Mvc2-2.2.0.0-release-net-3.5.zip
And referenced them in my MVC 2 project. My Global.asax.cs file looks like this (pretty much what the Ninject.Web.Mvc README says):
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;
namespace Mvc2 {
public class MvcApplication : NinjectHttpApplication {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo>();
return kernel;
}
}
}
And a home controller that looks like this:
using System;
using System.Web;
using System.Web.Mvc;
namespace Mvc2.Controllers {
public class HomeController : Controller {
private readonly IFoo foo;
public HomeController(IFoo foo) {
this.foo = foo;
}
public ActionResult Index() {
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
}
Now every time I run my project and visit '/' I get a yellow screen of death with a message that says "No parameterless constructor defined for this object." It seems Ninject is not resolving my Foo service and injecting it into HomeController. I imagine I'm missing something really obvious but I'm just not seeing it.
How do I get Ninject to inject Foo into the HomeController, and without using Ninject attributes?
Me: Could you provide a little more information about the IFoo service implementation? Does it have all of its own dependencies satisfied?
Myself: Hmm, no it doesn't. Turns out I didn't bind its dependencies. Boy, is that error message and stack trace misleading!
So my mistake was that I didn't bind one of the dependencies of the IFoo implementation and so Ninject failed silently and tried to continue on its merry way. Which is really unfortunate because it could lead to some really strange behavior once I deviate from a trivial setup. I guess my next question should be how can I get Ninject to fail as early as possible and provide good messaging about what's wrong? But for now I can at least get on with it.

Resources