MVC 3 tries to launch URL to View instead of controller action - c#

Sometimes when I launch my MVC 3 project it attempts to load the fully qualified URL for the view being rendered instead of the action within the controller (Which gives me a 404 error). Other times it works fine and actually hits the controller action like it's supposed to, but it's about 50/50.
The URL it hits sometimes is: http://localhost:xxxx/Views/Account/LogOn.cshtml
Here is the default route setup in the Global.asax file:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }
);
I also tried removing the /{id} parameter from the route as I don't feel it's needed for the logon screen.
Any ideas? Currently the project is setup pretty simply with the default action method LogOn in the AccountController etc. The only thing I did was change the controller and action in the global.asax file.

Try this :go to Project Properties > Web > Start Action
And check the Specific Page option - leaving the text box blank.

You are probably using Visual Studio and you probably are actively editing a .cshtml page when you hit debug.
Try launching the debugger when you are either looking at a code file or a file from a project that isn't in the startup project (ie, your EF/model project) and see if that launches the debugger to the correct URL.
There might be a setting in the project properties that specifies the startup URL. I'll look for it and edit this post if I find it.

I'm guessing you using cassini (builtin dev web server in VS.Net)? If so I get this all the time and seams to be a bug in VS.Net. Switch to IIS 7.5 and you don't get it any more

Related

mvc url redirection - Server Error in '/' Application

I'm going through the exercise from the book (just starting to learn MVC). I have made the following change to RouteConfig.cs file:
routes.MapRoute("Contact", "Contact/{*pathinfo}", new {
controller = "Home", action = "Contact" });
routes.MapRoute("About", "About/{*pathinfo}", new { controller =
"About", action = "About" });
The contact page works absolutely fine but the About just throws error when trying to access it via http://localhost:49899/About
Error: 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: /About
I cannot see any difference between those 2 lines of the code, can anybody point me to what I'm missing? This is a brand new project with all the default settings and scaffolding.
When you created the default project, all kinds of wizardry happened behind the scenes for you. The default project most likely came with an auto-generated HomeController, an auto-generated Home folder to contain Views that the Home Controller will call, some Actions that correspond to those Views.
You probably do not have a Controller named About. The route that you have defined for About is saying that to get to the About page you would go through the About controller and call the About Action. Most likely you need to hit the Home Controller and then the About Action.
P.S. MVC uses naming conventions to infer where things are. You'll probably find an About view in the view folder named Home. Are you seeing a pattern here?
Routing docs

MVC core routing not functioning as expected

So it's my first time setting up an netcore MVC based application. I've used MVC 4 in the past on plain old asp.net.
So i'm having issues with my routing. My application is an single page application (spa) that is accessible from the home controller on the index action. I can access this controller method fine, and my defaults are set so that this is navigated to at route: /.
I also have a second controller for authentication called AccountController. This controller's methods take and return JSON, rather then views. I can also access the methods on this controller from my application.
The issue i'm having lies in my next controller, which is the start of my API.
As such, i've put it in a folder called api inside my controllers folder. However, no matter what i try, i cannot seem to get the methods on the controller accessible. I have also tried moving it out of the api folder and just having in the route of the controllers folder.
The routing deffinition
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Core}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I've tried adding and removing the api definition, removing the api part, and adding a template for actions aswel, all to no effect.
The troublesome controller
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I've tried adding [Route(~routing here~)] annotations to this controller and its methods with no success either.
Folder structure
I should also mention that i've tried plenty of URL's to access this controller on:
/api/Core/
/Core/
/api/Core/Get
I've been wracking my brain for the best part of a day trying to get this sorted and i know i'm missing something obvious, i just can't for the life of me work out what it is.
Edit:
I've added a cut-down sample of my project to github at: https://github.com/lexwebb/aspnet-test if anyone would like a complete example
Edit 2
It appears that my example works, i'm going to add things in to see what breaks it
AFAIK, default route requires the {action} using as well.
Instead of "api" default routing, you may to use the following configuration for such type of controllers (RESTFul controller):
[Route("api/[controller]")]
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I found this Routing is ASP.NET Core article useful in the past.
So as it turns out, i had made a mistake in a totally unrelated place. I had renamed my project half way through the beginning stage of development, after i had build scripts in place. This led to the the wrong dll being referenced on the server when the code was ran, a version that had all of my routing EXCEPT the new one, of course.

Resource cannot be found (MVC)

I moved a solution from one machine to another and am having nightmares. I've got one problem left. The default page can't get served, it says Resource cannot be found. I have in the routeConfig.cs
routes.MapRoute("Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
I get Resource cannot be found.
I can access the default page by :-
http://example.com/home/index
The other questions don't seem to answer it.
EDIT: If I put the above line of code at the top of the Routing code, the default page works but other pages don't. If I put the code at the bottom, other pages work but the default page doesn't.
Try look in properties there is "Web" tab were you cat chose server and project URL, hope
If you have only default routing on RouteConfig file in development machine and keep getting 404, it seems that your problem comes from project's virtual path settings.
http://forums.asp.net/t/1893154.aspx?The+resource+cannot+be+found+404
If application is deployed on local host (or you have set Use local IIS
Web Server) then it means you have created a virtual directory named
"YourSite".
Right click your app project on VS, choose Properties, then go to "Web" part and set your site's virtual path on "Project Url".
For virtual directory problem on live IIS server, see here to add virtual directory into destination machine before deploying your app.
In addition, if you have custom routing rule, make sure the custom route placed properly on top of default routing rule.
The problem was that I had two Config Rules pointing to the same address. One of the other rules was pointing to the wrong controller. The wrong controller was erroring because I had set up the action, I had used the name of the controller as the action, thats a no-no. The above rule was correct but the incorrect rule was
routes.MapRoute(
name: "pagelist",
url: "pagelist",
defaults: new { controller = "pagelist", action = "pagelist", id = UrlParameter.Optional }
);
the action should have been Index.

Fresh Windows + VS2012 = MVC3 Problems

I just recently got a fresh install of Windows 7 on a my PC running VS2012/VS2010. I have an MVC3 project that ran just fine before I pulled it onto this PC to run. The project still compiles on this PC and I can navigate through my site while running the app in studio (2010 or 2012), but when I tried to POST from ANY form in ANY view and pass an ID by means of the URL like this:
<form id="ScriptForm" action="/MyApp/ControllerName/ActionName/#ViewBag.IDNumber" method="post">
...
</form>
...I got this error. I did some digging and playing around to try to fix this, ultimately taking these steps to try to resolve:
Actually installed ASP.NET via the Windows Components form in Control Panel
Changed the application to use IIS Express
Well, when I changed it to run under IIS Express, I started getting a different error.
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is
temporarily unavailable.
Most likely causes:
The directory or file specified does not exist on the Web server.
The URL contains a typographical error.
A custom filter or module, such as URLScan, restricts access to the file.
Things you can try:
Create the content on the Web server.
Review the browser URL.
Check the failed request tracing log and see which module is calling SetStatus. For more information, click here.
Detailed Error Information:
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002
Requested URL http://localhost:51596/MyApp/ControllerName/ActionName/1
Physical Path C:\CODE\MyApp\ControllerName\ActionName\1
Logon Method Anonymous
Logon User Anonymous
Request Tracing Directory C:\Users\cbarlow\Documents\IISExpress\TraceLogFiles\MYAPP
More Information:
This error means that the file or directory does not exist on the server. Create the file or directory and try the request again.
View more information ยป
It's almost as if it is not recognizing that this is a route and is trying to resolve the URL to a physical file (like 1.html) which obviously does not exist. But why isn't it "doing the MVC thing" and using the route? I have this in my global.asax:
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
);
}
And I know this is running because I can breakpoint it.
Specs:
Windows 7 | Visual Studio 2010/2012 | Microsoft MVC3 | IIS Express
I've read all these SO posts, none seem to apply in this situation or do not help (mostly, because they apply to actual aspx pages, where I am trying to load pages via controllers):
The HTTP verb POST used to access path '/' is not allowed
The HTTP verb POST used to access path is not allowed
The HTTP verb POST used to access path '/Membership/user/' is not allowed
The HTTP verb POST used to access path '/Main/[object Object]' is not allowed
The HTTP verb POST used to access path '[my path]' is not allowed
HTTP verb POST used to access path '/' is not allowed in Facebook app
Any ideas?
The problem is here (due to my lack of experience with MVC/CSHTML):
<form id="ScriptForm" action="/MyApp/ControllerName/ActionName/#ViewBag.IDNumber" method="post">
...
</form>
The MyApp used to work on my PC (I'm honestly not sure why it doesn't work now... maybe I had set something up for that name to resolve before?) but it no longer maps to anything. It DOES work on the server, but that's because there is indeed a mapping for "MyApp" in IIS. Simply changing this form to this:
<form id="ScriptForm" action="#Url.Content("~/ControllerName/ActionName/" + ViewBag.IDNumber)" method="post">
...
</form>
...does the job more elegantly and without errors.

Asp.net MVC routes ending with file extensions

I have an action that returns a Dynamically Generated image however I need the call to that action to end with a something.jpg.
This answer is very similar to my action Can an ASP.NET MVC controller return an Image?
MY action takes in a string called ID which I intend to pass the Something.jpg but my problem is that while this works locally when I deploy to my server and try it I get an IIS 7 404 error.
It looks like IIS is trying to find the final rather than calling the action, at no point is the action called.
I've tried adding the following to the global.asax to force it to call the action but to no avail.
routes.RouteExistingFiles = true;
routes.IgnoreRoute("Content/{*pathInfo}");
Could it be an issue with Mime types?
You may need to set your IIS 7 Application Pool in Integrated mode.

Categories