Pro ASP.net MVC Framework sample code not working - c#

This is from a very good book by Steven Sanderson
I am trying to follow the chapter 4 and trying to setup IOC on my mvc code from the code sample of the book but its not working.
I follow the code from page 97 to page 101 where I set up Inversion of Control and run the code but I get the following error.
A dialog box opens trying to search the following file:
c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\Windsor\WindsorContainer.cs
It seems like controllertype is null in the following line of code:
protected override IController GetControllerInstance(
System.Web.Routing.RequestContext requestContext,
Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
The exception happens at the above return statement saying " {"Value cannot be null.\r\nParameter name: service"}"
This happens to be in WindsorContainerFactory.
Routes looks as follows:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Products", action = "List", id = ""} // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}
}
Please help..
Thanks..

Your method is probably being called for requests that are not served by your app. For example for favicon.ico.
Make sure your controllerType is not null. If it is just return null and bypass the code that you added.
Different kind of browsers will make different "extra" requests to your site depending on how they cache. Also, if you are hosting the site with IIS vs Visual Studio Dev Server these might catch the request before it gets to your (e.g. IIS will server a .jpg file without having to letting go to your controller but the VS Dev Server might not)

You could try debugging the route.
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

So far I have found the following links addressing the same exact issue. I am copying them here for my own reference.
http://forums.asp.net/t/1559062.aspx?Pro+ASP.NET+MVC+-+setting+up+IOC+Castle+Windsor

First, I think it will be better if you let the relative link more than absolute link .
Second , check your browsers . I saw no error in your code . maybe different browsers will make it worse. Also, if you are hosting the site with IIS vs Visual Studio Dev Server these might catch the request . :D

Related

method is called 2 or 3 times in each request .NET MVC

I'm facing an issue in a project that I'm currently working on, I'm using ASP.NET MVC.
The scenario as follow:
- I have a login page (Username and Password).
- Whenever I navigate to localhost:5588/login, the below action method will be called 2 or 3 times (I'm using a Break Point inside this method to catch the call).
public ActionResult Login()
{
return View();
}
The question is, why this method is called 2 - 3 times whenever I enter the login page ?
P.S #1: Not only the Login page is being called 2-3 times, also each Action method have the same issue.
P.S: #2: I'm using the below route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
}
UPDATE:
This issue happens only on Google Chrome!
Issue might happen, because browser can pre-load page, before you hitting Enter.
In this thread posted solution, how you can understand that it is pre-load request: HTTP header to detect a preload request by Google Chrome
I once had this issue and found I had something like this
src="#"
in my image tag or check for any other markup that could be accidentally referencing the page like Script references, image references, css reference etc
Obviously somethings call your action method 3 times, strongly advice to open chrome developer tools, navigate to network and check the traffic, if they are XHR requests you can also track from where they came from, otherwise it is shoot in the dark.
This is the correct answer and this actually solved the issue. [Special Thanks to my friend Mohammad Aldayem for the great finding].
Based on an issue posted on Chromium Issue Tracker (https://bugs.chromium.org), the issue was in the "favicon.ico" in the _Layout.cshtml page. Because Chrome requests favicons on every request on pages that don't have a favicon.
And here are the links for this issue while using Google Chrome:
Link #1: https://bugs.chromium.org/p/chromium/issues/detail?id=64810
Link #2: https://bugs.chromium.org/p/chromium/issues/detail?id=39402

Routing in MVC application deployed on IIS

I have added the following code
public class RouteController : Controller
{
public ContentResult GetImpression()
{
// Do something
}
}
In RouteConfig class i have added the following
routes.MapRoute(
name: "Impression",
url: "imp",
defaults: new { controller = "Route", action = "GetImpression", id = UrlParameter.Optional }
);
I am expecting my http://mymachine/imp to work. What am i doing wrong? Do i have to do some settings in IIS as well?
For issues with routing I have always found the following tool from Phil Hacck to be invaluable in figuring out where I screwed up with my routing rules and what is getting called. There is nothing special you need to do in IIS to get things working. The one thing you probably should check is to ensure if your Application Pool is using version 4.0 and not version 2.0. Usually when you create a site in IIS it defaults the App Pool to 2.0.

Asp.Net MVC3 project Controllers and views are not working

This is kind of an odd problem that I am facing most of the time. I am creating a website and I have created a folder inside controllers folder in the project and I have created a controller inside that folder. So far it was Ok.
Then I created a view for that(Not manually)I can even navigate from controller to view in the code(This is to tell that the controller and the view are properly mapped in the code). But when I run the project and go to that URL its not working. It gives the following error. Although this is a more general error I have no thread to follow to get out of this mess.
But all the things that are created earlier is working smoothly. I have even tried a Default controller and created a view for that and then ran the program and it gives the same error.
Now I can not create new controllers and views(I can but they are not working). I am stuck with this all day long :(.
I feel like some configuration is missing. But I can not find out.
Since I am new to this I am totally lost. And I can not figure out what to do.
I am totally confused and I have no idea of what has happened.
Is it a settings problem in Visual studio?. And what should I do to make this work.
The error is this:
PS: I am working with Team Foundation server and I can not even do debugging. These controller methods are not called.
Have a look into MVC routing and modify your Global.asax.cs with this code:
public class MvcApplication : System.Web.HttpApplication
{
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 = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

I am having a problem where I try to open my ASP.NET MVC application but I get the ASP.NET error page which says this:
Server Error in '/' Application.
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: /EventScheduler/account.aspx/login
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053**
I am using the URL trick from this blog post and that is why I have the .aspx in the URL:
http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
It works on my other sandbox server (not a dev machine), and now I just deployed it to my production site as a new virtual directory, but for some reason it seems like it's actually looking for a .aspx file.
Any ideas? I think I must be forgetting a step.
I got the same error when building. The default is to use URLRoute settings for navigating. If you select the "Set as Startup Page" property by right clicking any cshtml page, that throws this error because there are always a routing to the current page under the Global.asax file.
Look at Project Properties for Startup Path and delete it.
I found the solution for this problem, you don't have to delete the global.asax, as it contains some valuable info for your proyect to run smoothly, instead have a look at your controller's name, in my case, my controller was named something as MyController.cs and in the global.asax it's trying to reference a Home Controller.
Look for this lines in the global asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
in my case i had to get like this to work
new { controller = "My", action = "Index", id = UrlParameter.Optional }
Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:
Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!
You should carefully review your Route Values.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
In this case, ensure you have your Controller 'Home' as the application will fail to load if there is no HomeController with Index Action. In My case I had HomesController and I missed the 's' infront of the Home. I Fixed the Name mismatch and this resolved the issue on both my local environment and on my server.
If you're running IIS 6 and above, make sure the application pool your MVC app. is using is set to Integrated Managed Pipeline Mode. I had mine set to Classic by mistake and the same error occurred.
The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:
Right click on Controller folder, and then select Add > Controller;
Select MVC 5 Controller - Empty;
Click in Add;
Put HomeController for the controller name;
Build the project and after Run your project again
I hope this help
Two Things Needs To Be Ensure:
1) Route should be proper in Global.ascx file
2) Don't forget to add reference of Controller Project in your Web Project (view is in separate project from controller)
The second one is my case.
Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.
I got the same error while building a MVC application.
In my case it happened because I forgot to add the string "Controller" in my controller name.
Error With
public class ProductType : BaseController
{
public ProductType()
{
}
}
Resolved
public class ProductTypeController : BaseController
{
public ProductTypeController ()
{
}
}
In your Project open Global.asax.cs then right click on Method RouteConfig.RegisterRoutes(RouteTable.Routes); then click Go To Definition
then at defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional}
then change then Names of "Home" to your own controller Name and Index to your own View Name if you have changed the Names other then "HomeController" and "Index"
Hope your Problem will be Solved.
Step 1 : Check to see if you have received the following update? http://support.microsoft.com/kb/894670 If you have you might want to follow this procedure and see if it works for you. It worked partially for me.
The item where it mentions the additional "/" to be removed is not entirely true but it did give me some insight to change my project properties just a bit.
step 2 : Right click on your properties for your Web Project in your Solun.
Select WEB > Choose Current Page instead of Specific Page.
step 3 : Go into your project where you keep your *.aspx's select a start page. (Should be the same as the current page or choose another one of your choice :) )
Hit Debug Run.
Suppose source code copy from other places.
Sometime, if you use Virtual Directory in your application url like:
http://localhost:50385/myapp/#/
No route will pick up the request.
solution:
Explicitly click the button 'create a virtual directory' in your project file.
Go to any page you want to see it in browser right click--> view in browser.
this way working with me.
Upon hours of debugging, it was just an c# error in my html view.
Check your view and track down any error
Don't comment c# code using html style ie
Open your Controller.cs file and near your public ActionResult Index(), in place of Index write the name of your page you want to run in the browser. For me it was public ActionResult Login().
Remember to use PUBLIC for ActionResult:
public ActionResult Details(int id)
{
return View();
}
instead of
ActionResult Details(int id)
{
return View();
}
you must check if you implemented the page in the controller
for example:
public ActionResult Register()
{
return View();
}
I had a similar problem. But I was working with Episerver locally with ssl enabled. When I wasn't getting a
Server Error in '/' Application.
I was getting a Insecure connection error.
In the end, for me, this post on PluralSight together with configuring the website urls, accordingly with the ssl link set up on the project's config, on Admin's Manage Website's screen solved the problem.
In my case, I needed to replace this:
#Html.ActionLink("Return license", "Licenses_Revoke", "Licenses", new { id = userLicense.Id }, null)
With this:
Return license
<script type="text/javascript">
function returnLicense(e) {
e.preventDefault();
$.post('#Url.Action("Licenses_Revoke", "Licenses", new { id = Model.Customer.AspNetUser.UserLicenses.First().Id })', getAntiForgery())
.done(function (res) {
window.location.reload();
});
}
</script>
Even if I don't understand why. Suggestions are welcome!
For me its solved follow the following steps :
One reason for this occur is if you don't have a start page or wrong start page set under your web project's properties. So do this:
1- Right click on your MVC project
2- Choose "Properties"
3- Select the "Web" tab
4- Select "Specific Page"
Assuming you have a controller called HomeController and an action method called Index, enter "home/index" in to the text box corresponding to the "Specific Page" radio button.
Now, if you launch your web application, it will take you to the view rendered by the HomeController's Index action method.
It needs you to add a Web Form, just go to add on properties -> new item -> Web Form. Then wen you run it, it will work. Simple
I had the same problem caused by my script below. The problem was caused by url variable. When I added http://|web server name|/|application name| in front of /Reports/ReportPage.aspx ... it started to work.
<script>
$(document).ready(function () {
DisplayReport();
});
function DisplayReport() {
var url = '/Reports/ReportPage.aspx?ReportName=AssignmentReport';
if (url === '')
return;
var myFrame = document.getElementById('frmReportViewer');
if (myFrame !== null) {
if (myFrame.contentWindow !== null && myFrame.contentWindow.location !== null) {
myFrame.contentWindow.location = url;
}
else {
myFrame.setAttribute('src', url);
}
}
}
</script>

ASP.NET MVC in a virtual directory

I have the following in my Global.asax.cs
routes.MapRoute(
"Arrival",
"{partnerID}",
new { controller = "Search", action = "Index", partnerID="1000" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
My SearchController looks like this
public class SearchController : Controller
{
// Display search results
public ActionResult Index(int partnerID)
{
ViewData["partnerID"] = partnerID;
return View();
}
}
and Index.aspx simply shows ViewData["partnerID"] at the moment.
I have a virtual directory set up in IIS on Windows XP called Test.
If I point my browser at http://localhost/Test/ then I get 1000 displayed as expected. However, if I try http://localhost/Test/1000 I get a page not found error. Any ideas?
Are there any special considerations for running MVC in a virtual directory?
IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so?
This happens because IIS 6 only
invokes ASP.NET when it sees a
“filename extension” in the URL that’s
mapped to aspnet_isapi.dll (which is a
C/C++ ISAPI filter responsible for
invoking ASP.NET). Since routing is a
.NET IHttpModule called
UrlRoutingModule, it doesn’t get
invoked unless ASP.NET itself gets
invoked, which only happens when
aspnet_isapi.dll gets invoked, which
only happens when there’s a .aspx in
the URL. So, no .aspx, no
UrlRoutingModule, hence the 404.
Easiest solution is:
If you don’t mind having .aspx in your
URLs, just go through your routing
config, adding .aspx before a
forward-slash in each pattern. For
example, use
{controller}.aspx/{action}/{id} or
myapp.aspx/{controller}/{action}/{id}.
Don’t put .aspx inside the
curly-bracket parameter names, or into
the ‘default’ values, because it isn’t
really part of the controller name -
it’s just in the URL to satisfy IIS.
Source: http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
If you are doing this on Windows XP, then you're using IIS 5.1. You need to get ASP.Net to handle your request. You need to either add an extension to your routes ({controller}.mvc/{action}/{id}) and map that extension to ASP.Net or map all requests to ASP.Net. The http://localhost/Test works because it goes to Default.aspx which is handled specially in MVC projects.
Additionally, you need to specify http://localhost/Test/Search/Index/1000. The controller and action pieces are not optional if you want to specify an ID.
There are a number of considerations when using virtual directories in your application.
One is particular is that most browsers will not submit cookies that came from one virtual directory to another, even if the apps reside on the same server.
Try set virtual path: right click on mvc project, properties, web tab, there enter appropriate location.

Categories

Resources