asp.net web pages. Default route - asp.net

How I can set up my site (asp.net web pages) to get urldata for default page?
site.com/default/1
this work,
but site.com/1 return 404 error.
In web forms this work fine, but in web pages no

In Solution Explorer, there is a file called as App_Start. You can configure RouteConfig.cs file whatever you want. There is the example of Route 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 }
);
}

If you have a default.cshtml that is always the default start page, even if it´s not listed in the list with default pages under Settings. I guess it´s because how the routing works in ASP.NET Web Pages.
If you want a index.html as start page, you need to add it to the list with default pages, and remove the default.cshtml if you have that.
see This link
<defaultDocument enabled="true">
<files>
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
</files>
</defaultDocument>
Here Similar Post

Related

IIS 8.5 returns 404 for {controller}/{action}/{id}

I have an ASP.NET MVC app that is deployed to several servers on IIS 10. All routes work correctly there.
On IIS 8.5, routes that follow {controller}/{action}/{id} return a 404. If the route is changed to {controller}/{action}?id={id}, the correct result is returned with a 200 code.
Is there a setting that must be turned on for IIS 8.5 to correctly map {controller}/{action}/{id} to an MVC controller?
My route config:
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 }
);
}
Relevant sections of web config:
<system.web>
<compilation targetFramework="4.6.1" />
<httpRuntime targetFramework="4.5" maxUrlLength="99999" maxQueryStringLength="99999" />
<customErrors mode="RemoteOnly" />
<authentication mode="None" />
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
I've tried the suggestions in this question but they did not fix the 404s.
Something seemed to have gotten borked in IIS for just that site. Deleting and redeploying the site fixed the problem

I can't get templateUrl to work

I'm new to Angular and I'm using Angular-UI-Router with ASP.NET MVC 4.
app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('about', {
url: '/',
template: 'HELLO WORLD'
});
}]);
this works fine. HELLO WORLD is displaying so i know that everything is set up rather correctly.
but when i try templateUrl instead of template say:
app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/'); //if you go to incorrect url it'll go back to home
$stateProvider
.state('about', {
url: '/',
templateUrl: 'Home/About.html'
});
}]);
nothing displays. I'm using almost a clean slate default template from scratch.. picking the "Internet Application" from default templates.. in my directories i have
Views --> Home --> About.html
I also have About.cshtml and I've tried that and it doesn't work neither. Help please!
ASP.NET MVC Views doesn't allow direct access to .html files of it. You need to allow the access from the web.config by adding handlers in system.webServer
Code
<system.webServer>
<handlers>
<add name="JavaScriptHandler" path="*.js" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<add name="HtmlScriptHandler" path="*.html" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
Or the other way around would be you could create one new static folder other than Views that will have an html files in it. You could directly access the URL eg. static/about.html
For more details refer this Answer

Http 500 error causes blank page in deployed MVC application

I am having a bit of an issue here. I have an MVC application that has been deployed to IIS 7 on Windows Server 2008. In Visual Studio 2012, whenever an internal server error occurs i.e. http 500, it shows the page I designed for it. However, when I deploy it to IIS, it shows a blank page which could be very annoying because one does not see the application's page at all. All I need is for the error page to display instead of the blank page that it currently displays as a deployed application in the client's site. I can then work on fixing the error in Visual Studio. Kindly pardon me if I broke any rules of S.O.
Here is what I have setup in my ErrorController.cs
public ActionResult ForbiddenPage()
{
Response.StatusCode = 403;
Response.TrySkipIisCustomErrors = true; // add this line
return View();
}
//
// GET: /Error/
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true; // add this line
return View();
}
//
// GET: /Error/
public ActionResult InternalServerError()
{
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true; // add this line
return View();
}
In web.config, this is what I have:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." ...
</handlers>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="403" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/ForbiddenPage" />
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />
<remove statusCode="500" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/InternalServerError"/>
</httpErrors>
</system.webServer>
My RouteConfig.cs Looks like this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "LogIn",id = UrlParameter.Optional }
);
routes.MapRoute(
"403-ForbiddenPage",
"{*url}",
new { controller = "Error", action = "ForbiddenPage" }
);
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "Error", action = "PageNotFound" }
);
routes.MapRoute(
"500-InternalServerError",
"{*url}",
new { controller = "Error", action = "InternalServerError" }
);
The View that should be displayed is below:
#{
ViewBag.Title = "Internal Server Error";
Layout = "~/Views/Shared/_LayoutError.cshtml";
}
<h2></h2>
<div class="list-header clearfix">
<span>Internal Server Error</span>
</div>
<div class="list-sfs-holder">
<div class="alert alert-error">
An unexpected error has occurred.... click<a href ="/Home/LogIn"><i><u>here</u></i>
</a> to login again..
</div>
</div>
If there is any thing that I should have included to aid you in proffering a solution, please let me know in the comments.
Yes I found the solution,
Thanks ppittle, your link to Kev's answer helped. I tried the suggestion in the answer but it didn't work in my scenario. However, the link posted by Kev in the answer helped alot. What worked was the setting in the applicationHost.config in your production server [where IIS is].
Look for a file called applicationHost.config at this location:
C:\Windows\System32\inetsrv\config
Change the "overrideModeDefault" setting below from Deny to Allow.
This is what worked for me. Thanks StackOverflow!
I had this same issue, but didn't see this answer anywhere:
The user my application was running under didn't have permission to access the database that was configured in the web.config. There was no indication that this was the problem that I could find.
The way I found this was by deploying in DEBUG instead of Release, which then showed me the error message.

How to implement Google reCaptcha in an MVC3 application?

Can anyone explain how to have reCaptcha functionality like stackoverflow in my MVC3 application.
And how can you customize that?
I use the Google ReCaptcha and it works very well and is very simple to implement.
Note that if you are using Https be sure you have the current version of the dll (1.0.5.0 at this time)
You need to create an account on the Google Recaptcha site and get a set of public and private keys. Add the keys to your web project main web.config file:
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="ReCaptchaPrivateKey" value="put your private key value here" />
<add key="ReCaptchaPublicKey" value="put your public key value here" />
</appSettings>
Now use NuGet and install the reCAPTCHA plugin for .NET
Then, go to your web.config file inside of your VIEWS folder. Add this line:
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Recaptcha"/>
</namespaces>
Then, in your view that you want to show the captcha, add the using statement at the top of your file
#using Recaptcha;
then add this to your view:
<div class="editor-label">
Are you a human?
</div>
<div class="editor-field">
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
#Html.ValidationMessage("captcha")
</div>
In your controller action you will need to modify the signature to accept the captcha results:
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ForgotPassword(CheckUsernameViewModel model, bool captchaValid, string captchaErrorMessage) {
if (!Membership.EnablePasswordReset)
throw new Exception("Password reset is not allowed\r\n");
if(ModelState.IsValid) {
if(captchaValid) {
return RedirectToAction("AnswerSecurityQuestion", new { username = model.Username });
}
ModelState.AddModelError("", captchaErrorMessage);
}
return View(model);
}
Following those steps have allowed me to implement captcha on several pages and it works smoothly. Note that the parameter names on the controller action MUST BE NAMED CORRECTLY:
bool captchaValid, string captchaErrorMessage
If you changed these parameter names you WILL get an error at runtime when your form posts back to the controller action.
I would recommend using a Honeypot Captcha. The experience for your users is MUCH better. There is one fore ASP.NET MVC here http://nuget.org/packages/SimpleHoneypot.MVC
PM> Install-Package SimpleHoneypot.MVC4
There is a WiKi on how to get it up here: https://github.com/webadvanced/Honeypot-MVC/wiki
Just start out with the Getting Started section.
You can read more about the general idea of a Honeypot Captcha here: http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx

How to set the Default Page in ASP.NET?

Is there any section or code which allows us to set default page in web.config?
For example, when people first visit my website, I want them to see CreateThing.aspx rather than Default.aspx.
The solutions I already know:
Put this line of code => Response.Redirect("CreateThings.aspx") in Default.aspx Page_Load event but this method is really naive.
We can use IIS (default page configuration,) but I wanna do the same thing over on my ASP.NET application.
This could be another solution for now:
<defaultDocument>
<files>
<clear />
<add value="Default.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
</files>
</defaultDocument>
If using IIS 7 or IIS 7.5 you can use
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
https://learn.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/
Tip #84: Did you know… How to set a Start page for your Web Site in Visual Web Developer?
Simply right click on the page you want to be the start page and say "set as start page".
As noted in the comment below by Adam Tuliper - MSFT, this only works for debugging, not deployment.
Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.
<add verb="GET" path="default.aspx" type="RedirectHandler"/>
Make sure Default.aspx does not exists
physically at your application root.
If it exists physically the
HttpHandler will not be given any
chance to execute. Physical file
overrides HttpHandler mapping.
Moreover you can re-use this for pages other than default.aspx.
<add verb="GET" path="index.aspx" type="RedirectHandler"/>
//RedirectHandler.cs in your App_Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
public RedirectHandler()
{
//
// TODO: Add constructor logic here
//
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Redirect("CreateThings.aspx");
context.Response.End();
}
#endregion
}
If you are using forms authentication you could try the code below:
<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/">
</forms>
</authentication>
if you are using login page in your website go to web.config file
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="index.aspx" >
</forms>
</authentication>
replace your authentication tag to above (where index.aspx will be your startup page)
and one more thing write this in your web.config file inside
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
</files>
</defaultDocument>
</system.webServer>
<location path="index.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
You can override the IIS default document setting using the web.config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPageToBeSet.aspx" />
</files>
</defaultDocument>
</system.webServer>
Or using the IIS, refer the link for reference http://www.iis.net/configreference/system.webserver/defaultdocument
I had done all the above solutions but it did not work.
My default page wasn't an aspx page, it was an html page.
This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes
Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute(""); // This was the line I had to add here!
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Hope this helps someone, it took me a goodly while to find the answer.
I prefer using the following method:
system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>

Resources