Asp.net core and IE 11 rendering page issue - asp.net-core

This is the weirdest error i have seen so far, and im not sure what i am doing wrong here.
I have asp.net core application. I wanted to wire-up different layout page to Error view instead of default _layout.cshtml. So here are the steps i followed:
1> Created a new asp.net core web application using VS 2015 community using default project template.
2> I added a new _ErrorLayout.cshtml layout page into Views\Shared Folder.
_ErrorLayout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>My Application</title>
</head>
<body>
<div>
#RenderBody()
</div>
</body>
</html>
3> Then i wired up Error.cshtml to new _ErrorLayout.cshtml layout.
Error.cshtml
#{
Layout = "~/Views/Shared/_ErrorLayout.cshtml";
}
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
4> Just for local testing purpose, in startup's configure method, i wire-up /Home/Error view for development environment.
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/Home/Error");
app.UseBrowserLink();
}
}
5> For testing pupose throw exception in Home's Index method.
Home.cs
public class HomeController : Controller
{
public IActionResult Index()
{
throw new Exception();
}
}
Now whenever application starts it goes to error page as expected.
Issue
Error view has unwanted text. I just want header and a message. So i deleted everything below <h2>.
Modified Error.cshtml
#{
Layout = "~/Views/Shared/_ErrorLayout.cshtml";
}
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
Now if i run application i get Http 500 error
I press F12 in IE 11 and check the response. It looks correct but i dont know why page does not render. Below is the captured response in IE11
Notes
This is only happening in IE 11. Google chrome shows error page on application startup.
If put the deleted text back in error view then IE 11 works.

Related

dotnet core 2.1 error in rendering view after adding html code

I have a razorview which uses a layout with name ReportsLayout. I was pulling configuration strings by injecting IConfiguration into the Layout as well as page views as below.
_Layout View
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
Page View
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
#model DayFuelSalesView
#{ Layout = "~/Views/Shared/_ReportsLayout.cshtml"; }
It was working fine until I added some more code to the razorview page which is basically pure html code.
After adding the code, during the debugging, the debugger show error as below in the web browser while trying to open the page.
This is the first time I am seeing such kind of error and I am unable to get it to work.
Any help is appreciated.
Try to check if you have #Render xxx{} in your Page View.If so,you need to add #await RenderSectionAsync("xxx", required: false) to your _Layout View.Try to refer to the Sections in the official doc.For example,if you have the following code in your view:
#section Scripts
{
...
}
You need to make sure you have #await RenderSectionAsync("Scripts", required: false) in your _ReportsLayout.cshtml.

Howto debug JavaScript inside ASP .Net Core 3.1 MVC applications (Razor view - *.cshtml)?

I have latest Visual Studio 2019 16.5.4 Enterprise.
I've just created an ASP .Net Core 3.1 MVC application from a template (with default settings).
And I've added some JavaScript code to a Home Page's Index.cshtml:
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
#section Scripts {
<script>
function GetJSON_Simple() {
var resp = [];
return resp;
}
debugger;
var simpleData = GetJSON_Simple();
</script>
}
And I'm not able to debug JavaScript code (breakpoints inside GetJSON_Simple function body or on var simpleData = GetJSON_Simple() is never hit). I've tried both Chrome and MS Edge (Chromium).
According to this article (Debug JavaScript in dynamic files using Razor (ASP.NET) section):
Place the debugger; statement where you want to break: This causes the
dynamic script to stop execution and start debugging immediately while
it is being created.
P.S. I've already have Tools->Options->Debugging->General with turned on Enable JavaScript Debugging for ASP.NET (Chrome and IE) checkbox and of course I'm compiling in Debug.
My test project is attached
Howto debug JavaScript inside ASP .Net Core 3.1 MVC applications
(Razor view - *.cshtml)?
In fact, it is already a well-known issue. We can not debug the js code under Net Core razor page but only for code in separate js or ts files. See this link.
Solution
To solve it, I suggest you could create a new single js file called test.js and then reference it in razor page and then you can hit into js code when you debug it.
1) create a file called test.js and migrate your js code into it:
function GetJSON_Simple() {
var resp = [];
return resp;
}
debugger;
var simpleData = GetJSON_Simple();
2) change to use this in your cshtml file:
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
#section Scripts {
<script scr="xxx/test.js">
</script>
}
3) clean your project, then rebuild your project and debug it and you will hit into Js code.
Another way is to explicitly define the source mapping name for the script directly in your javascript code via a sourceURL comment.
<script>
...your script code
//# sourceURL=blah
</script>
The script in that block will show up in Chrome with the value you specified. You can then view and debug just like a normal .js file.
This is especially useful if you don't want to refactor an existing codebase that has embedded javascript in the cshtml files or really ANY codebase that has javascript loaded on the fly.
Live Example
You can actually see an example with the built-in javascript runner here. Just click 'Run Snippet' and then search for "blahblah" in your Page sources. You should see this:
alert("test");
//# sourceURL=blahblah

Blazor hosted - authorize immediately before displaying application

Can anybody give me a helping push to get my hosted Blazor application (Client, Server and Shared) to request a login immediately, before the application is initially shown. I want the experience that a user must log in before accessing the application at all.
My starting point is the Blazor Webassembly (hosted) template with Api Authorization (Individual User Accounts)
Using the Authorize attribute on either server-side actions or a client-side Razor page will not initiate the authentication flow before the specific action/page with the Authorize attribute is being requested by the user. How would I go about having the authorization flow kicked off as the first thing, before the application is even displayed for the first time?
I am sure this is possible and even trivial for somebody more savvy than me. Can anybody give me a shove in the right direction, please?
I created a control RedirectToLogin.razor
#inject NavigationManager Navigation
#code {
protected override void OnInitialized()
{
String thisPage = Navigation.Uri.Replace(Navigation.BaseUri, "~/");
Navigation.NavigateTo($"Identity/Account/Login?returnUrl={thisPage}");
base.OnInitialized();
}
}
And then inserted it into the mainlayout.razor
<div class="container-fluid">
<AuthorizeView>
<Authorized>
<NavigationLogger />
<ContextMenuMouseClick>
<MenuTopBar />
<NavMenu />
<SubPageContainer>
#Body
</SubPageContainer>
</ContextMenuMouseClick>
</Authorized>
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeView>
</div>
So when the layout is loaded and it is in the NotAuthorized state it will redirect to the login page and after authorising will return to the page it was trying to access.
Hope this helps.
The Blazor Client is bootstrapped from a static index.html in the wwwroot. In the Server project this is mapped to an Endpoint in the Startup.cs, basically a catch-all to all endpoints not taken by your Razor Pages or Controllers:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
For your scenario:
Create a new layout in Server, say _LayoutBlazor.cshtml
Re-create the contents of the index.html from the Client. Note that the _framework files from the Client are copied to the Server wwwroot upon build:
:
<app>Loading...</app>
<script src="#Href("~/_framework/blazor.webassembly.js")"></script>
Create a new Razor page and put the "Authorize" tag on it and use the _LayoutBlazor.
Remove the endpoints.MapFallbackToFile("index.html"); from Startup.cs
Mark Gould has created a proof of concept here: RazorBlazor

How to sign out over HttpContext in server-side Blazor

I access the HttpContext in a Blazor server-side view to manually log out. I added this line to Startup.cs: services.AddHttpContextAccessor(); and inject it in the view with #inject IHttpContextAccessor HttpContextAccessor.
I've got a log out button which tries to execute this code:
await HttpContextAccessor.HttpContext.SignOutAsync("Cookies");
but I get the following error message:
System.InvalidOperationException: 'Headers are read-only, response has already started.'
How can I prevent this error?
If you scaffolded Identity and overridden the old "LogOut.cshtml" from when you created the project via template, the Logout button won't logout. Assume you've used the default IdentityUser model. I ran into this issue and just wanted to add this if anyone else had this problem as well. I'm using Blazor Server with .Net 5.0.3's template. You can remove the Logout.cshtml.cs after as well.
Replace this \Areas\Identity\Pages\Account\LogOut.cshtml
#page
#model LogoutModel
#{
ViewData["Title"] = "Log out";
}
<header>
<h1>#ViewData["Title"]</h1>
#{
if (User.Identity.IsAuthenticated)
{
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
</form>
}
else
{
<p>You have successfully logged out of the application.</p>
}
}
</header>
Replace with
#page
#using Microsoft.AspNetCore.Identity
#attribute [IgnoreAntiforgeryToken]
#inject SignInManager<IdentityUser> SignInManager
#functions {
public async Task<IActionResult> OnPost()
{
if (SignInManager.IsSignedIn(User))
{
await SignInManager.SignOutAsync();
}
return Redirect("~/");
}
}
This tripped me up too, but you need the logout functionality to be on a Razor Page (not a Blazor component). Create a Logout page and put your logout code in the OnGetAsync() method.
Your logout button can then link to the logout page.
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/4316/A-Demonstration-of-Simple-Server-side-Blazor-Cookie-Authentication.aspx - this is a helpful example
Don't use IHttpContextAccessor.
I guess that you're using ASP.NET Core Blazor authentication and authorization new system. If not, then start with it right now. Live is too short to be wasted over other things. This is the best product created so far for Blazor's authentication and authorization, and it is based on the Identity UI (This is not Blazor, of course). Additionally, there are a couple of Components which enable controlling the flow of authentication and authorization in your application, such as displaying a "Log in" button and a "Log out" button in your layout, interchangeably altering depending on your authentication state, etc.
Please, go to this page and start learning this excellent system, and then come here for specific issues you face:
https://learn.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.0&tabs=visual-studio
Hope this helps...

Kendo UI Upload Async Error

I downloaded a trial version of Kendo.UI, so logging onto the forums, at this stage is not possible, hoping someone on here can help me solve this problem.
I'm trying to implement the async upload onto a basic MVC 4 application. I've added a reference to the Kendo.UI.MVC wrappers, and added the necessary namespace Kendo.UI.MVC to both web.config files (root and under Views).
If I implement a basic uploader on my landing view (index.cshtml) it works fine:
<form action="/Home/Save" method="post">
#(Html.Kendo().Upload().Name("files"))
<input type="submit" value="Submit" />
</form>
However, as soon as I add the Save() method to Async, I get an "index was out of range" exception. I know it's the save method, because if I just add "AutoUpload(true)" without an action reference, it does not throw an exception. If I just add "Remove("Remove", "Home")" it still shows the Select button, without an error, but the "Save("Save", "Home")" method keeps throwing the mentioned exception.
I followed the examples that ship with the trial to the letter and it should web working, yet it does not.
View (index.cshtml):
#(Html.Kendo()
.Upload()
.Name("files")
.Async(async => async
.Save("Save", "Home")))
-- Error is being thrown on the above statement
#(Html.Kendo()
.Upload()
.Name("files")
.Async(async => async
.AutoUpload(true)))
-- this line works
Controller (HomeController):
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFile> files)
{
// I just want the break-point to be hit
// does not due to IndexOutOfRange exception being thrown
return Content("");
}
}
The only thing that seems wrong is the Razor syntax:
(#Html.Kendo()
should be
#(Html.Kendo()
I was able to run your code with this small change.
Updated the MVC templates for Visual Studio and it works. Thanks.