By default a Razor Page app goes to Home/Index
Is there a way to change this to Home/App?
This is quite easy in MVC, but Razor pages using a different routing setup and thus MVC routing does not apply.
I would think it would be in options somewhere, but I don't see it:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Account/Manage");
options.Conventions.AuthorizePage("/Account/Logout");
options. ??SetDefaultPage??
});
I have tried this:
options.Conventions.AddPageRoute("/App", "");
But now two default routes are found and an error is generated:
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:
Page: /App
Page: /Index
It's possible to resolve this error by removing Pages/Index.cshtml from the project, but I wanted to keep that page as well.
In my case the ambiguity was caused by Pages/Index.cshtml left in project.
This worked:
options.Conventions.AddPageRoute("/App", "");
remove or rename Pages/Index.cshtml
Pretty sure it isn't possible. The docs say the runtime controls the search for Index as the default. I couldn't find where that happens in the current release, but IndexFileName is a static in the new internal PageRouteModelFactory class added to the upcoming release:
private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension;
It doesn't seem like it would be difficult to just add a config property to RazorPagesOptions, though. The ASP.NET guys are pretty responsive, I'd open a request as a GitHub issue and hope for the best.
I solved the issue by using Microsoft.AspNetCore.Rewrite:
Then adding code to replace the default Index action, in my case with Portfolio:
var options = new RewriteOptions()
.AddRedirect("^", "portfolio"); // Replace default index page with portfolio
More detailed article about rewrite options - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?tabs=aspnetcore2x
Another way is to simply redirect from the Index OnGet method, like so:
public class IndexModel : PageModel
{
public IActionResult OnGet()
{
return Redirect("/Welcome");
}
}
Notice that I have change the return type of the OnGet method.
Related
I can't use RedirectToPage for any of the pages in the identity folder in my razor pages app.
If I use: return RedirectToPage("/Identity/Account/Manage/ChangePassword");
What I got is an error:
InvalidOperationException: No page named '/Identity/Account/Manage/ChangePassword' matches the supplied values.
In the case of using Redirect itself, routing works fine but I need to route some values so I have to use RedirectToPage
If you want to use RedirectToPage, try the below code:
return RedirectToPage("/Account/Manage/ChangePassword");
/Account/Manage/ChangePassword means that we are looking for the ChangePassword.cshtml file in the Manage folder in the Account folder of the Pages folder.
return RedirectToPage("/Privacy");
/Privacy means that we are looking for the Privacy.cshtml file in the Pages folder.
The RedirectToPage() method is referring to a Razor cshtml "page" rather than a html page in the browser. So it expects the parameter to refer to a cshtml page in your project.
update:
If you add in IndexModel class to call page in Indentity folder you can try :
public IActionResult OnGet()
{
return RedirectToPage("/Account/Manage/ChangePassword", new { area = "Identity" });
}
I want to load my application at http://localhost:52856/CRUD/Products/List so then i can start working on the List.cshtml file instead of loading Index.cshtml at http://localhost:52856 .
Look i know i can just put a button at the index file so then it can redirect to path or use the navbar, but personally i don't want to do that every single time.Just load the application at the file.cshtml i want. But How can i do it?
If you don't like my comment you could do the following in Index.cshtml.cs
public IActionResult OnGet()
{
return new RedirectToPageResult("/CRUD/Product/List");
}
1. Include MVC as a service into our app.
we can optionally use another method called AddRazorPagesOptions() like so:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Customer/Index", "");
});
Within that AddRazorPagesOptions() method, we can set things like route conventions and the root directory for pages. It turns out that, to set a default route for a page.
2. remove or rename Pages/Index.cshtml
Hi I'm getting strange behavior in our AspNetCore 2.1 application using Razor Pages. When an exception escapes from a Razor Page action like OnGet the application crashes. The exception never reaches any middleware. It looks like the application seems is crashing somewhere in the internal PageActionInvoker.Next method.
I can't paste the code as it far too much. But the following will crash the application:
public async void OnGet() {
await Task.CompletedTask; // normally we await something else
throw new Exception("Boom!");
}
Note:
We are:
combining Views and Razor Pages. The Views are part of the 'older' section of the application.
we are allowing Razor Page area's.
Do we have to configure some feature?
Are we missing something? Does someone have suggestions?
FOUND IT
Nothing special. Well AspNetCore accepts async void OnGet and everything works fine UNTIL an exception is raised.
using the following fixed it.
public async Task OnGetAsync() {
It seems that even AspNetCore doesn't handle the following construction well:
public async void OnGet() {
...
}
Even though it's accepted and seems to be working possible exceptions are not handled correctly.
The correct way to do this is:
public async Task OnGetAsync() {
....
}
Don't know whether this classifies as a AspNetCore bug ... in that sense maybe it should be rejected like many other things. Oh well ... bug fixed.
When using a .NET MVC to build a website, when do I need to include a new route's info in RouteConfig.cs?
I have seen there is one default route pre-configured and registered in the RouteConfig.cs file like this:
public class RouteConfig
{
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 }
);
}
}
When I created a new controller I saw that, without writing any route info in RouteConfig.cs, the corresponding view was rendered in my browser.
Even after creating a few more controllers, like testcontroller, that I accessed from test views, still without writing anything regarding a route for testcontroller, their views rendered properly.
As these views all render without editing anything in RouteConfig.cs, can you give me a few examples when I do need to write route info in RouteConfig.cs?
The RouteConfig exists for when you want to do a 'non default' route in MVC. As you can see, a lot of your ActionResults will be rendered by matching that route specified there. Ultimately you may be able to create an entire site and not even have to touch the RouteConfig.cs! It's only when you start to want different routes for use cases that you might find yourself diving in there.
An example for when you might need to edit it, is if you had an Area exclusively for blogs and wanted to do something along the lines of:
/Blog/Post/1234/my-blog-post
By default that wouldn't match the default config. In areas the default route config is prefixed by the Area name and then follows the usual standard like so.
/{area}/{controller}/{action}/{id}
In order to get override this we can write the following:
context.MapRoute(
"Blog",
"Blog/Post/{id}/{name}",
new { action = "Index",controller="Post" },
new { id = #"\d+" }
);
It's worth noting that in newer versions of MVC (5 onwards) we have access to the Routing attribute which is an easier and more accessible way to handle routing across controllers and actions.
Article: MVC5.1 Features, Attribute Routing..
Article: MVC5 Attribute Routing via David Hayden
Additional Reading for Routes in ASP.NET MVC
ASP.NET MVC Routing Overview
ASP.NET Typical Routing - URL Patterns
I'm new to web development and I'm trying to implement the Kendo UI editor with an image browser to insert into the document on an MVC 4.5 page. the editor is working fine, however, when i click the insert image button i gt a 403 forbidden popup message.
I've created a custom image browser controller pointing to ~/Content/images.
and in my view, i am using the custom browser controller within my code
#(Html.Kendo().EditorFor(m => m.QuestionText)
.Encode(false)
.HtmlAttributes(new { style = "width: 100%; height: 200px" })
.Name("EditQuestionText")
.Tools(tools => tools.Clear().InsertImage())
.ImageBrowser(imageBrowser => imageBrowser
.Image("~/JFA/QuestionImages/{0}")
.Read("Read", "JFAImageBrowser"))
)
I've compared my code to the sample project from Kendo for the EditorFor (which will browse the folder) but can find no discernible differences... I also cannot find much in the way of other people who are having this problem so i suspect there is a setting that i cannot find that is causing my issue, any help would be GREATLY appreicated
my image browser (taken directly from the demo)
public class JFAImageBrowserController : EditorImageBrowserController
{
private const string contentFolderRoot = "~/Content/images";
public override string ContentPath
{
get
{
return contentFolderRoot;
}
}
additionally, using Fiddler the click event for the "Insert Image" button is
GET /JFA/JFAImageBrowser/Read?path=%2F HTTP/1.1
where as the demo is
POST /ImageBrowser/Read HTTP/1.1
I don't know why the demo is using a POST where as mine is using a GET, unless this is because of the overridden image browswer
That code looks fine. Can you make sure your JFAImageBrowser controller looks something like this?
public class BlogImagesController : EditorImageBrowserController
{
//
// GET: /BlogImage/
public ActionResult Index()
{
return View();
}
public override string ContentPath
{
get { return AssetFilePaths.BlogContentPath; }
}
}
It's important that it inherits from EditorImageBrowserController
Also, a 403 may mean that the user doesn't have permission to access the directory. Check the permissions for the user you're running as.
It turns out my problem was in the _Layout page. I was using bundling and either
A) I made some error when setting up the bundling
-or-
b) the bundling didn't work as expected/intended.
either way i added the individual script/java script references and it works as expected.
Here is the solution to this problem
the page this issue fixed was it kendo forum
http://www.telerik.com/forums/implementing-image-browser-for-editor
and the direct link for the demo
http://www.telerik.com/clientsfiles/e3e38f54-7bb7-4bec-b637-7c30c7841dd1_KendoEditorImageBrowser.zip?sfvrsn=0
and if this demo didn't work you can see this sample i made from above
https://www.mediafire.com/?9hy728ht4cnevxt
you can browse the editor through HomeController and the action name is homepage (home/homepage)
& I think that the error was in different uses of paths between the base controller & child controller you make.