Mvc3 web app routing directly on index.cshtml - asp.net-mvc

I have created and host nvc3 web app
now problem is when I open my www.abc.com
it is opening index.cshtml i.e home page of mvc web app
but I dont want that to be open when I open www.abc.com
I have one static page called index.htm should be open first
in mvc3 Global.asax code:
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
);
}
How can I render to http://www.abc.com/mypage.html ?
what should I please help.

ashuthinks,
Based on your revised comments for the question. If you just want to show the 'Under contruction' type page with no links, then you can modify the web.config and add an app_offline.htm file. here's what those changes would look like:
web.config (bare bones):
<?xml version="1.0"?>
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
app_offline.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Your site title</title>
</head>
<body>
<div>
<span>Your Company name</span>
<h1>Sorry, server maintenance in progress </h1>
<h2>Please contact John Doe on 000 123 456789 for further information</h2>
</div>
</body>
</html>
when you need to put the site live, simply rename the above files to web.config_offline and app_offline.htm_offline and bring your 'normal' web.config into play. There are of course many ways to skin this cat but this has worked well with previous projects that I've worked on.
see:
http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx
for further details.

Related

Standalone Blazor app as a Razor Class Library

Is it possible technically to have a full webassembly Blazor application as a Razor Class Library and then consume it in another ASP.NET project regardless of the consumer be MVC, Razor Pages, or Blazor app? Is it possible to define the routing within the Razor Class library?
I'm working on a project that is going to be published as a Nuget package. This package should be used in a variety of ASP.NET projects which are implemented as MVC, Razor Pages, or even Blazor.
I figured out how to get it running. I am using .NET 5.0.
First create a new Solution with a Razor Class Library project (Check the checkbox Support pages and views).
And create a MVC project.
In Startups.csadd the following:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddRazorPages();
services.AddServerSideBlazor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Also make sure you have app.UseStaticFiles(); in your Configure method.
Then, in your Razor Class Library, you can copy and paste the Pages, Shared folders and all other razor files from the example Blazor webassembly project. Also don't forget the wwwroot css folder and add your own wwwroot folder to your RCL.
In the Pages folder also create a new cshtml file. This will be the entry point to your Blazor app.
Example code:
#page
#using PROJECTNAME
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blazor WebAssembly Prerendered</title>
<base href="~/" />
<link href="/_content/PROJECTID/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="/_content/PROJECTID/css/app.css" rel="stylesheet" />
#*https://learn.microsoft.com/de-de/aspnet/core/blazor/components/css-isolation?view=aspnetcore-5.0#razor-class-library-rcl-support*#
<link href="/_content/PROJECTID/PROJECTNAME.bundle.scp.css" rel="stylesheet" />
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
</body>
</html>
<script src="_framework/blazor.server.js"></script> <!--blazor.webassembly.js didn't work-->
The important parts are the <base href="~/" /> and the _framework/blazor.server.js.
If you don't map this page to be at the root, like #page "/" you have to make sure all the static content is mapped to the project-id correctly.
Also make sure the paths in the example projects NavMenu.razor are correct if you don't use / as the root. Has to be correct in the Razor Components too.
If you have problems with the _Imports.razor file, try adding the NuGet package Microsoft.AspNetCore.Components.WebAssembly
Also add the correct namespace for your shared folder, in the example project it's PROJECTNAME.Shared. Change it accordingly.
Here's a blogpost that helped me get things the right way: https://blog.joelving.dk/2020/02/reusable-ui-and-interchangable-hosting-models-in-blazor/

Accessing CDN bundles on different ASP.Net MVC site

This is a follow-up question to this: ASP.Net MVC 5 - Deploy separate CDN site with bundled JavaScipt and CSS
I want to serve up my JavaScript and CSS bundles from a second ASP.Net website, so I have done the following.
Main website (ASP.Net MVC website that has not JS or CSS resources)
CDN website (ASP.Net MVC website that has all JS and CSS resources but not much else)
CDN Website Web.config extract
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
CDN Website Bundle Config
public static class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
}
}
Main Website Bundle Config
public static class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css", "http://[CDN website]/Content/css"));
//BundleTable.EnableOptimizations = true;
}
}
Main Website Layout View
<!DOCTYPE html>
<html>
<head>
#Styles.Render("~/Content/css")
</head>
<body>
#RenderBody()
</body>
</html>
Result
The HTML produced by the main website doesn't render the <link> tag for the CSS. However, if I turn on bundle optimizations (see commented out code in Main Website Bundle Config), then the <link> tag appears but looks like this:
<link href="/Content/css?v=" rel="stylesheet">
Navigating to http://[CDN website]/Content/css in the browser loads the appropriate CSS.
Navigating to http://[Main website]/Content/css in the browser loads an empty page.
Am I doing this the incorrectly? I don't want to reference the CDN website URL directly because I want the versioning that comes with the MVC bundler.
I ended-up using the following solution for the CDN website.
https://stackoverflow.com/a/26402383/2663033
The main website then used the appropriate MVC route of the CDN website for the style "href" and the script "src", which redirected to the appropriately versioned content or script bundle.

angularjs with cshtml page only not html pages with web api 2

I'm having asp. net mvc4 project. Angularjs is integrated.
I have already built HTML pages and WEB APIs 2 as per previous requirements.
Now for some reason i have to go with CSHTML pages. previously I had only web api project template so i couldnt go with cshtml pages as ONLY MVC controller can return partial page(cshtml) but i was using only web apis...
So changed whole project template and so now i can have mvc controllers... ...
In short, currently I have mvc4 project with already built web apis and html pages.....
I just want to use CSHTML pages instead of using HTML pages rest things should be as they are...
Is it possible?
I may sound silly but it is need right now. help would be greatly appreciated...
Web apis, cshtml pages and angularjs only. not web apis, html pages and angularjs.
If I replace html pages by cshtml, how would angular route get affected?
Well, this is how I use it.
There is index.cshtml like this
#using System.Web.Optimization
#inherits System.Web.Mvc.WebViewPage
#{ Layout = null; }<!DOCTYPE html>
<html data-ng-app="MyProject">
<head>
<title data-ng-controller="TitleCtrl" data-ng-bind="Title">My Project</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
#Styles.Render("~/Content/min/css")
</head>
<body class="body" id="body">
<div class="body" data-ui-view="body"></div>
#Scripts.Render("~/js/angular")
#Scripts.Render("~/js/MyProject")
</body>
</html>
NOTE: using angular UI-Router, that's why ui-view is in palce
But still there must be HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
// below I do some tricks to make app running on
// http://mydomain/app as well as on
// http://mydomain/app/ (see the / at the end)
var root = VirtualPathUtility.ToAbsolute("~/");
var applicationPath = Request.ApplicationPath;
var path = Request.Path;
var hasTraillingSlash = root.Equals(applicationPath
, StringComparison.InvariantCultureIgnoreCase)
|| !applicationPath.Equals(path
, StringComparison.InvariantCultureIgnoreCase);
if (!hasTraillingSlash)
{
return Redirect(root + "#");
}
// my view is not in Views, but in the root of a web project
return View("~/Index.cshtml");
}
}
So, this way I can use power of Bundle configureation (javascript, css) ... while starting angular at http://mydomain/app or http://mydomain/app/. Check also similar here
Also in global.asax, we should configura ASP.NET MVC:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("fonts*.woff");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id =UrlParameter.Optional}
);
}
while web API should be:
const string IdPattern = #"\d+|[A-Za-z]{1,2}";
public static void SetRouting(HttpConfiguration config)
{
// some custom routes
...
// and a default one
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}"
, constraints: new { id = IdPattern }
, defaults: new { id = RouteParameter.Optional }
);

Web.config urlMappings - works for local pages, not remote pages

I have a MVC4/.Net 4 website running on IIS 7.5. In my web.config file I have the following in my block:
<urlMappings enabled="true">
<add url="~/2013calendar" mappedUrl="~/CustomerService/RequestPocketCalendar" />
<add url="~/teachers" mappedUrl="http://www.somexternalsite.com/teachers/" />
</urlMappings>
The local redirects all work great, but anything that is redirecting off the site, such as the /teachers link in the above example return "http://www.somexternalsite.com/teachers" is not a valid virtual path.
What am I missing here?
If I'm not mistaken, the mappedUrl field is a path relative to the root of the application. As such, "http://www.somexternalsite.com/teachers/" is not valid.
If you'd like to configure this to redirect, I would just create a "Teachers" action in your root controller, then use the following:
return Redirect("http://www.somexternalsite.com/teachers");
Well I ended up creating a page to handle external redirects such as follows:
redirect.aspx
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
var page = Request.QueryString["page"];
Response.Redirect("http://"+page);
}
</script>
So in my web.config I have external files referenced as such:
<add url="~/teachers" mappedUrl="~/redirect.aspx?page=www.somexternalsite.com/teachers/" />
Works great!

jsf 2.0 and welcome-files

I have some problems with the default URL that jsf shows:
The url is displayed like this:
www.URL.com/PROYECT_NAME/
And I want something like this
www.URL.com/PROYECT_NAME/home
I sent up the welcome file like this.
<welcome-file-list>
<welcome-file >faces/views/home.xhtml</welcome-file>
</welcome-file-list>
So what I really want is that when jsf shows the welcome file show and url like this www.URL.com/PROYECT_NAME/home or the complete route faces/views/home.xhtml.
I know is a dumb question but Im stock in it
It is possible to achieve that using a filter-based servlet extension like PrettyFaces.
It is simple to use, has good documentation and examples, but to illustrate your case you could do something like this:
Download prettyfaces.jar and add to your classpath. Usually /WEB-INF/lib folder.
Add a pretty-config.xml file containing the URL mappings to the /WEB-INF folder.
Example of pretty-config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<pretty-config xmlns="http://ocpsoft.com/prettyfaces/3.3.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ocpsoft.com/prettyfaces/3.3.3 http://ocpsoft.com/xml/ns/prettyfaces/ocpsoft-pretty-faces-3.3.3.xsd">
<url-mapping id="home">
<pattern value="/home" />
<view-id value="/home.xhtml" />
</url-mapping>
</pretty-config>
To redirect to this mapping from a controller you should use a string like pretty: + url-mapping-id.
Example of controller bean:
#ManagedBean
#ViewScoped
public class HomeBean
{
public String goHome()
{
return "pretty:home";
}
}
That's it. Whenever you fire a request, if PrettyFaces filter finds the url mapping pattern /home it will display the view id home.xhtml but keep the URL as /home. Pretty.
Also, as a suggestion, for your welcome-file-list you could add only index.html.
Example of web.xml welcome-file-list tag:
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
And add an index.html file like this to your application root folder.
Example of index.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Application</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="0;url=/myapplication/home" />
</head>
<body>
<h3>Loading...</h3>
</body>
</html>
By doing this, whenever someone requests your application it will get a fast loading page and will be redirected to /home.
I hope it helps.

Resources