ASP.NET MVC in a virtual directory - c#

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.

Related

Asp.net MVC Catchall Routing in a Sub Application

I have an MVC application with a sub application running another MVC project in IIS. Both use the same version framework and run on separate application pools.
My problem is, I cannot get the sub application to work inside this virtual application folder of the root site. I get a 403.14 Forbidden error. If I enable directory listing on the sub application I just get a list of the MVC application files.
I think, I have narrowed the problem down to routing; The sub application has a custom catchall route which handles all requests to the site, its a CMS application. There are no other routes registered. Here is the code for my custom route:
RouteTable.Routes.Insert(0,new CmsRoute(
"{*path}",
new RouteValueDictionary(new
{
controller = "Page",
action = "Index"
}),
new MvcRouteHandler()));
Running this application outside of the main root application in its own site, it works fine and all requests are handled by my custom route. But as soon as I try run this as a sub application the route handler is never hit.
If I add the standard default MVC route that comes out of the box:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Then MVC kicks in and tries to find a match route for the request.
So my question is why will my catchall route not work while running in a sub application in IIS ?
Note: I have tried prefixing the url in my custom route with the name of the virtual application folder, but it still does not work, example:
RouteTable.Routes.Insert(0,new CmsRoute(
"subapplication/{*path}",
new RouteValueDictionary(new
{
controller = "Page",
action = "Index"
}),
new MvcRouteHandler()));
Use sub domain rather than sub application if that doesn't hurt your purpose.
But, if you are bound to do that,remember this the application and sub application have to be running on the same version of .NET.
In addition, there is a parent/child relationship with the web.configs - so the child application will inherit the parents web.config unless told not to do so using 'inheritInChildApplications' in the configs. But, that might also give you headache of clashing with child. here is a solution to this(headache) if you want to try parent/child relationship . http://articles.runtings.co.uk/2010/04/solved-iis7-validateintegratedmodeconfi.html
When you send a request from a client to an application, it doesn't get transferred to another application (like your sub-application) unless you specifically make the call. That's why your sub-application works fine when you access it directly but fails when you try to reach it through the parent the way you're doing it. Routing is about requests and it's the application that got the request that is responsible for the routing issues.
So what you need to do is make an actual redirect to your sub-application. Your sub-application should have a separate URL (a sub-domain will be fine). The code should look like this:
public ActionResult YourAction() //Action in the main application
{
var subAppUrl = "http://yourSubApplicationUrl?AnyOtherQueryStringSetToPassData";
return Redirect(subAppUrl);
}
If you're calling the action using Ajax, then it should be:
public JsonResult YourAction() //Action in the main application
{
var subAppUrl = "http://yourSubApplicationUrl?AnyOtherQueryStringSetToPassData";
return Json(new {url = subAppUrl });
}
and the corresponding JQuery:
$.post("#Url.Action("YourAction")", function(data) {
window.location = data.url;
});
Your SubApplication it's already the Path:
RootApp /
SubApp1 /SubApp1
SubApp2 /SubApp2
routes.MapRoute(
"SubApp1", // Route name
"{*url}", // URL with parameters
new
{
controller = "Controller",
action = "Action",
id = UrlParameter.Optional
}
);
And.. you should remove on the root app the MapRoute to your SubApp1 if already managed!

C# View page URL

I've created a controller, called ClientController.cs and VS automatically created the necessary View files in /Views/Client. But I wanted to get these pages in a different URL... So, it is /Client but I need it at /admin/client.
What should I change?
Thank you!
It's not clear what your functionality will be in the long run, but here are a few options that allow you to get the URL format you want:
Perhaps you want a controller called "Admin" and an action called "Client". This would give you a path of /Admin/Client by default
Alternatively, you can change your route maps. For example, the following with route /Admin/Client to the Index of your Client controller:
routes.MapRoute(
"Default", // Route name
"Admin/Client/{action}", // URL with parameters
new { controller = "Client", action = "Index" } // Parameter defaults
);
Or maybe even go a far as using "Areas", depending on what you need. Have a Google of that if you're interested in learning more
If you want it to be admin/client, then using the default routing you should create an Admin Controller with an ActionResult method called Client. Your views folder should have an admin folder with your client view inside.
I haven't done a lot of MVC but i believe this is what you do.

How to change url for MVC4 WebSite?

I need to change the URL on my address bar.
I looked for URL Rewrite but as far as I've seen it works for a request like this:
url.com/mypage.aspx?xp=asd&yp=okasd
and transforms that into:
url.com/mypage/asd/okasd
http://www.iis.net/downloads/microsoft/url-rewrite
That's not my scope. I already have MVC Routes working with url.com/mypage. The problem is that when I type that URL I am redirected (that's the behavior I want) to url.com/otherpage/actionX?param=value. The problem is that I still want the address bar to show url.com/mypage. Will URL Rewrite work for that?
I am asking because I don't know if it will work since it's an internal redirect (RedirectToAction) instead of a 'regular' access.
In case someone wonders why I can't make a route for that, as explained in my question I alread have one rule for that url.com/mypage that redirects to a 'router' which decides what action to call.
I've seen some questions, but I don't think they cover my specific problem:
MVC3 change the url
C# - How to Rewrite a URL in MVC3
UPDATE
This is my route:
routes.MapRoute(
"Profile", // Route name
"{urlParam}", // URL with parameters
new { controller = "Profile", action = "Router" } // Parameter defaults
);
Inside Router action I redirect to the correct action according to some validation done on urlParam. I need this behavior since each action returns a different View.
Updated my tags since I am now using MVC4
Thanks.
I once had to run a php site on a windows box. On the linux box it originally ran, it had a rewrite defined to make site process all request in only one php file (index.php).
I've installed and configured URL Rewrite with following parameters
Name : all to index.php
Match URL ------------------------------
Requested URL : Matches the Pattern
Using : Regular Expressions
Pattern : (.*)
Ignore Case : Checked
Conditions -----------------------------
Logical Grouping : Match All
Input : {REQUEST_FILENAME}
Type : Is Not a File
Action ---------------------------------
Action Type : Rewrite
Action Properties:
Rewrite Url : /index.php?$1
Append Query String : Checked
Log Rewritten URL : Checked
this makes all requests to site (except files like css and js files) to be processed by index.php
so url.com/user/1 is processed on server side as url.com/index.php?/user/1
since it works on server side client url stays same.
using this as you base you can build a rewrite (not a redirect).
Server.Transfer is exactly what you need, but that is not available on MVC.
On the MVC world you can use the TransferResult class defined in this thread.
With that... you add code to your ROUTE action that process the urlParam as always and instead of "redirecting" (RedirectToAction) the user to a new URL, you just "transfer" him/her to a new action method without changing the URL.
But there it a catch (I think, I have not tested it)... if that new page postbacks something... it will NOT use your router's action URL (url.com/mypage), but the real ACTION (url.com/otherpage)
Hope it helps.
In my opinion,you can try following things:
Return EmptyResult or RedirectResult from your Action method.
Also,you need to setup and construct outbound route for URL that you required.
Secondly, if these didn't work,the crude way to handle this situation is with Div tag and replacing the contents of Div with whatever HTML emitted by Action method. I am assuming here that in your problem context, you can call up jquery ajax call.
Hope this Helps.
The problem you have is that you redirect the user ( using 302 http code) to a new location, so browser ,reloads the page. you need to modify the routes to point directly to your controller. The route registration should be routes.MapRoute("specific", "my page", new { controller = "otherpage", action="actions", param="value"}).
This route should be registered first

Multiple Controllers with one Name in ASP.NET MVC 2

I receive the following error when trying to run my ASP.NET MVC application:
The request for 'Account' has found the following matching controllers:
uqs.Controllers.Admin.AccountController
MvcApplication1.Controllers.AccountController
I searched the project for MvcApplication1.Controllers.AccountController to remove it, but I can't find a match.
I try to registered a route to fix it:
routes.MapRoute(
"LogAccount", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = "" },
new string[] { "uqs.Controllers.Admin" } // Parameter defaults
);
but that didn't solve it.
Multiple types were found that match
the controller named 'Account'.
How I can fix this problem?
If you refactor your project and change the default Namespace and Assembly from "MVCApplication1" to "uqs", you may end up with 2 assemblies in your bin directory (the new one and the old one). You can get this error because the AccountController is in both assemblies.
Clean your bin directory of the old MVCApplication1.dll.
You can't have more than one controller named Account in your application, even in different namespaces.
You have to have these controllers split up by Area (a feature in ASP.NET MVC 2).
If you conduct a Find for AccountController you'll find all controllers named Account in your application; and move them off into different Areas if you want both of them, or delete one.
Had this same problem. Cleaned the bin and I was good to go.
A slightly confusing variation on the problem (similar in that it causes the same error message) can occur even with namespaces supplied. MVC 3 I think is a little pickier than MVC 2 on this front.
Short Answer:
Make sure the namespace of your controller is in fact the namespace specified in the MapRoute call!!
Long Answer:
I have 3 areas : default ("") / Facebook / Store and they each have AdminController
I have the route mapped like this (for my default area):
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Gateway", action = "Index", id = UrlParameter.Optional },
new string[] { "RR.Controllers.Main" }
);
A request to /admin gave the following error :
Multiple types were found that match
the controller named 'admin'. This can
happen if the route that services this
request ('{controller}/{action}/{id}')
does not specify namespaces...
The request for 'admin' has found the
following matching controllers:
RR.FacebookControllers.AdminController
RR.Controllers.AdminController
RR.StoreControllers.AdminController
But wait a minute! Didn't I specify the controller namespace.... ? What's going on.... ?
Well it turned out my default area's admin controller namespace was RR_MVC.Controller instead of Rolling_Razor_MVC.Controller.Main.
For some reason in MVC 2 this didn't give a problem, but in MVC 3 it does. I think MVC 3 just requires you to be more explicit when there's potential ambiguities.
AccountController is automatically generated by the ASP.NET MVC Visual Studio template. It is located in Controllers\AccountController.cs. Try searching for it in the project and delete it.
I had this problem...
Solved by removing a project reference in one of the .csproj files

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>

Categories

Resources