Blazor Allow Anonymous For Razor Page - c#

I have a .net cor 3.1 Blazor server project. I use the default identity system in this project. I want to access a specific razor page without login. How do I do that? Any Idea?
I tried adding #attribute [AllowAnonymous] to the razor page. But it did not work for me
_Host.cshtml
page "/"
#using Microsoft.AspNetCore.Authorization
#namespace has.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#attribute [Authorize]
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>has</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="css/custom_styles.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="_content/AntDesign/css/ant-design-blazor.css" rel="stylesheet" />
<link href="_content/Blazor.ContextMenu/blazorContextMenu.min.css" rel="stylesheet" />
<script src="_content/BlazorInputFile/inputfile.js"></script>
<script src="~/js/site.js"></script>
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script src="_content/AntDesign/js/ant-design-blazor.js"></script>
<script src="_content/Blazor.ContextMenu/blazorContextMenu.min.js"></script>
<script src="https://kit.fontawesome.com/863157cf0e.js" crossorigin="anonymous"></script>
</body>
</html>
App.razor
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="#routeData" DefaultLayout="#typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<Error404 />
</LayoutView>
</NotFound>
</Router>
<AntContainer />
</CascadingAuthenticationState>

I found an answer. I created another _Host.cshtml with #attribute [AllowAnonymous] in a separate folder inside of the Pages folder and I put my razor page in that folder.
Add #layout PublicLayout to your anonymous access component. In my case, MyAnonymousComponent.razor. PublicLayout is PublicSection/PublicLayout.razor
My project structure is like this
MyProject
-Pages
-Section1
-Section2
-Shared
_Layout.cshtml
-PublicSection // This folder has anonymous access components
_Host.cshtml
_Layout.cshtml
MyAnonymousComponent.razor
PublicApp.razor
PublicLayout.razor
_Host.cshtml
-Shared
MainLayout.razor
App.razor
_Imports.razor
Program.cs
Startup.cs
PublicSection/_Host.cshtml
#page "/publicsection"
#using has.Pages.PublicRazor
#using Microsoft.AspNetCore.Authorization
#namespace has.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#attribute [AllowAnonymous]
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<base href="~/PublicSection" />
// rest is same as Original _Host.cshtml file
</head>
<body>
<app>
<component type="typeof(PublicApp)" render-mode="ServerPrerendered" />
</app>
// rest is same as Original _Host.cshtml file
</body>
</html>
PublicApp.razor
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="#routeData" DefaultLayout="#typeof(PublicLayout)" />
</Found>
<NotFound>
<LayoutView Layout="#typeof(PublicLayout)">
<Error404 />
</LayoutView>
</NotFound>
</Router>
<AntContainer />
</CascadingAuthenticationState>
PublicLayout.razor
#inherits LayoutComponentBase;
<Content Class="site-layout-background content-pan">
#Body
</Content>
#code {
}
Startup.cs
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("~/PublicSection/{**segment}","/PublicRazor/_Host");
endpoints.MapFallbackToPage("/_Host");
});
...

Related

Create a cards carousel slider with blazor

I have been working with blazor server for some time now but I have not been able to achieve how to create a cards carousel with it. I want to use slick slider in my project. I have downloaded slick and jquery, linked jquery, slick.min.js, slick.js, slick-theme.css and slick.css but nothing seems to work. I've tried looking on the web for some solutions but none of these are clear to understand. I've also done this with html, css and js and it works just fine. Please anyone help me with this because i believe a carousel is a very important component in a website.
#using Microsoft.AspNetCore.Components.Web
#namespace Blogger.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en" class="scrollbar-thin scrollbar-track-transparent scrollbar-thumb-slate-500">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link href="css/site.css" rel="stylesheet" />
<link href="Blogger.styles.css" rel="stylesheet" />
<link rel="stylesheet" href="css/slick.css">
<link rel="stylesheet" href="css/slick-theme.css">
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
#RenderBody()
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="js/jquery.js"></script>
<script src="js/slick.min.js"></script>
<script src="js/slick.js"></script>
<script src="js/all.min.js"></script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
Perhaps it is not working for you because you have implemented both the normal and the minified file?
<script src="js/slick.min.js"></script>
<script src="js/slick.js"></script>

Blazor-Server sidenav/sidebar for Identity/Account/Manage that looks like NavMenu.razor

Default Blazor project is very inconsistent when it comes to UI. For blazor components, there is a sidenav. But for account manage /Identity/Account/Manage there is no sidenav as that is .cshtml not .razor page.
I know that to have consistent UI I have to have probably two side nav and maintain exactly the same layout for both of them. Still, maybe there is already some example of sidenav for /Identity/Account/Manage that looks exactly as that available for blazor components?
The most welcome solution is use existing blazor navbar (Shared/NavMenu.razor) in account management (/Identity/Account/Manage) pages
I have created a PR against your sample on GitHub. The change is to the _Layout.cshtml used by Identity - it's not perfect, but shows the technique.
_Layout.cshtml
#using Microsoft.AspNetCore.Hosting
#using Microsoft.AspNetCore.Mvc.ViewEngines
#inject IWebHostEnvironment Environment
#inject ICompositeViewEngine Engine
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - BlazorAuthTemplate</title>
<base href="~/" />
<link rel="stylesheet" href="~/Identity/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/Identity/css/site.css" />
<link href="css/site.css" rel="stylesheet" />
</head>
<body>
<app>
<div class="sidebar">
<component type="typeof(BlazorAuthTemplate.Shared.NavMenu)" render-mode="ServerPrerendered" />
</div>
<div class="main">
<div class="top-row px-4 auth">
<div class="d-sm-inline-flex flex-sm-row-reverse">
#{
var result = Engine.FindView(ViewContext, "_LoginPartial", isMainPage: false);
}
#if (result.Success)
{
await Html.RenderPartialAsync("_LoginPartial");
}
else
{
throw new InvalidOperationException("The default Identity UI layout requires a partial view '_LoginPartial' " +
"usually located at '/Pages/_LoginPartial' or at '/Views/Shared/_LoginPartial' to work. Based on your configuration " +
$"we have looked at it in the following locations: {System.Environment.NewLine}{string.Join(System.Environment.NewLine, result.SearchedLocations)}.");
}
</div>
About
</div>
<main role="main" class="content px-4 pb-3">
#RenderBody()
</main>
</div>
</app>
<script src="~/Identity/lib/jquery/dist/jquery.min.js"></script>
<script src="~/Identity/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/Identity/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
<script src="/_framework/blazor.server.js"></script>
</body>
</html>

CSS Not Working In _Host.chstml In Blazor Server

Here I have blazor server app, in app I have two _Host.cshtml, one for website which is default _Host.cshtml and another for admin panel that is _HostAdmin.cshtml. Both of them have separate css and js file. I too have separate layout, for website I have Mainlayout.razor which should use _Host.cshtml and for admin panel I have AdminLayout.razor which should use _HostAdmin.cshtml .
Now, the problem is that when I add new razor component and use AdminLayout.razor layout the view doesnot use css and js of _HostAdmin.cshtml.
Below is my _HostAdmin.cshtml
#page "/Admin"
#namespace MCQ.Pages._Pages_Admin__HostAdmin
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Admin Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="~/Admin" />
<link rel="stylesheet" href="/Adminlte/plugins/fontawesome-free/css/all.min.css" />
<link rel="stylesheet" href="/Adminlte/plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="/Adminlte/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
<link rel="stylesheet" href="/Adminlte/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
<link rel="stylesheet" href="/Adminlte/plugins/jqvmap/jqvmap.min.css">
<link rel="stylesheet" href="/Adminlte/dist/css/adminlte.min.css">
<link rel="stylesheet" href="/Adminlte/plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="/Adminlte/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet" href="/Adminlte/plugins/summernote/summernote-bs4.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
<component type="typeof(App)" render-mode="ServerPrerendered" />
</div>
<script src="~/Adminlte/plugins/jquery/jquery.min.js"></script>
<script src="~/Adminlte/plugins/jquery-ui/jquery-ui.min.js"></script>
<script>$.widget.bridge('uibutton', $.ui.button)</script>
<script src="~/Adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="~/Adminlte/plugins/chart.js/Chart.min.js"></script>
<script src="~/Adminlte/plugins/sparklines/sparkline.js"></script>
<script src="~/Adminlte/plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="~/Adminlte/plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
<script src="~/Adminlte/plugins/jquery-knob/jquery.knob.min.js"></script>
<script src="~/Adminlte/plugins/moment/moment.min.js"></script>
<script src="~/Adminlte/plugins/daterangepicker/daterangepicker.js"></script>
<script src="~/Adminlte/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<script src="~/Adminlte/plugins/summernote/summernote-bs4.min.js"></script>
<script src="~/Adminlte/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="~/Adminlte/dist/js/adminlte.js"></script>
<script src="~/Adminlte/dist/js/pages/dashboard.js"></script>
<script src="~/Adminlte/dist/js/demo.js"></script>
</body>
</html>
Below is Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
endpoints.MapFallbackToPage("~/Admin/{*clientroutes:nonfile}", "/_HostAdmin");
});
You state
Now, the problem is that when I add new razor component and use AdminLayout.razor layout the view doesnot use css and js of _HostAdmin.cshtml.
and I assume your question is "Why".
You're adding a new razor component page to the existing application - probably with a route of something like "/admin/myadminpage". You're misunderstanding what's actually going on.
_Host.cshtml loads the SPA, but that's the only get/post that happens. Navigation after that is changing out components in the DOM. Loading a component with the layout AdminLayout just changes out the Layout component. There's no toing and froing with the server.
What you are trying to do requires a reload of the SPA. You could use:
NavigationManager.NavigateTo("/admin/myadminpage", true);
Also even if you do force a reload, the Fallbacks are in the wrong order - the default before the specific.
endpoints.MapFallbackToPage("/_Host");
endpoints.MapFallbackToPage("~/Admin/{*clientroutes:nonfile}", "/_HostAdmin");

MVC1000 Use of IHtmlHelper.Partial may result in application deadlocks. Consider using <partial> Tag Helper or IHtmlHelper.PartialAsync

Trying to make a web app using .Netcore When I run the application I get this error. Help me
This is not a errors but a warning. But help me to resolve
I added my code below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/css/bootstrap.css" rel="stylesheet" />
<link href="~/css/sidebar-nav.min.css" rel="stylesheet" />
<link href="~/css/animate.css" rel="stylesheet" />
<link href="~/css/default.css" rel="stylesheet" />
<link href="~/css/style.css" rel="stylesheet" />
</head>
<body class="fix-header fix-sidebar">
<div id="wrapper">
#Html.Partial("AdminPartials/_TopMenu")
#Html.Partial("AdminPartials/_Sidebar")
<div id="page-wrapper" style="min-height:600px">
<div class="container-fluid">
#RenderBody()
<hr />
<footer class="footer text-center">© #DateTime.Now.Year | Powered by Techguy</footer>
</div>
</div>
</div>
#RenderSection("scripts", required: false)
<script src="~/js/jquery.min.js"></script>
<script src="~/js/bootstrap.min.js"></script>
<script src="~/js/sidebar-nav.min.js"></script>
<script src="~/js/custom.js"></script>
</body>
</html>
In case you are looking just how to update from #Html.Partial to <partial>:
#Html.Partial("AdminPartials/_TopMenu")
#Html.Partial("AdminPartials/_Sidebar")
Should be changed to
<partial name="AdminPartials/_TopMenu" />
<partial name="AdminPartials/_Sidebar" />
More details here: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/partial-tag-helper?view=aspnetcore-2.2
use
#await Html.PartialAsync("_partialView", new List<Model>())
For the ones how as me are not so familiar with regex. You can do this change easily in whole solution using Find&Replace. It should do the job in most cases.
Find: \#Html.Partial\(\"(.*?)\"\),
Replace: <partial name="$1" />,
option "Use regular expressions" checked
and
Find: \#Html.Partial\(\"(.*?)\", (.*?)\),
Replace: <partial name="$1" for="#($2)"/>,
option "Use regular expressions" checked

Ajax.BeginForm results in redirect to partial view instead of in-place

My Search.cshtml has a div named "search-results" that is to be updated. SearchResults is the action name. I have done this many times on MVC2/VS2008 projects, but this is my first using MVC3 and VS2010.
The problem is, instead of my search result being rendered in my div, it clicking submit is redirecting me displaying my partial as a standalone page.
I have read that this may be because Ajax is not enabled. My _Layout.cshtml looks like this:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<script src="#Url.Content("~/Scripts/2011.2.712/jquery-1.5.1.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/themes/base/jquery.ui.core.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet"  type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery.ui.theme.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/main.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/2011.2.712/jquery-1.5.1.min.js")" type="text/javascript"></script>
#(Html.Telerik().StyleSheetRegistrar().DefaultGroup(group => group.Add("telerik.common.css").Add("telerik.transparent.css").Combined(true).Compress(true)))
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
#(Html.Telerik().Menu()
.Name("menu")
.Items(menu => {
menu.Add().Text("Home").Action("Index", "Home");
menu.Add().Text("About").Action("About", "Home");
menu.Add().Text("Employees").Action("List", "Employee");
}))
</div>
<div id="main">
#RenderBody()
<div id="footer">
</div>
</div>
</div>
#(Html.Telerik().ScriptRegistrar().DefaultGroup(group => group.Combined(true).Compress(true)))</body>
</html>
Do I need to add MicrosoftMvcAjax.js or jquery.unobtrusive-ajax.js in? My web.config (root) contians the following:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
If I add MicrosoftMvcAjax.js in at the end of the element, I get an error sayning namespace 'Type' is undefined error from the first line of MicrosoftMvcAjax.js:
Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_AjaxOptions=function(){return {};}
What am I missing here. I am sure my code is fine, as it copied alsmost verbatim from my MVC2 projects.
You forgot to include the jquery.unobtrusive-ajax.js script to your page (adjust the path as necessary):
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
As far as Microsoft*.js scripts are concerned, they are obsolete in ASP.NET MVC 3 and should no longer be used unless you are porting some legacy application. They have been replaced by jQuery.
Ok, figured out my problem.
I was calling Ajax.BeginForm with the AjaxOption OnSuccess pointint to a js function that updated my place holder. But this is not needed, with unobtrusive. Once I removed the OnSucces from the Ajax options everything started working.
~S

Categories

Resources