Static Files in Header - c#

I am trying to include static files resides outside of the wwwroot folder to _Layout.chtml. How to make this happen? For example, I have header.html and footer.html under include folder which is located under the project folder, I create a _Layout.chtml and want to add the header and footer files as partial views? Below is the Program.cs code:
using Microsoft.Extensions.FileProviders; //access files outside webroot
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(#"C:\MyProjects\myprograms\WebApplication1\include"),
RequestPath = new PathString("/include")
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
My _Layout.cshtml file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Html.Partial("/include/header")
</head>
<body>
<div>
#RenderBody()
</div>
#Html.Partial("/include/footer")
</body>
</html>
When I start the application, I receive the error message as below:
InvalidOperationException: The partial view '/include/header' was not found. The following locations were searched: /include/header
Please advice! Thanks.

The Html.Partial method is used render the MVC view not the html static file, I don't suggest you use it to render the html. This has no difference between render a MVC partial view and the static html file.
If you want to include some html file inside your layout, I suggest you could consider using Jquery to achieve your requirement.
Like this answer said:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
B is another html.

Related

Integrate React to an MVC ASP.NET project

i have to use React component in my MVC project. I found out that is possible by installing some Packages with NuGets. I installed:
-React.Web.Mvc4
-JavaScriptEngineSwitcher.V8
-Microsoft.ClearScript.V8.Native.win-x86 and x64
I tried to follow tutorials online but seem that i miss something important cause the simple string that i want to show doesn't appear.
Maybe is only an error of setting so i leave here the codes and the directory folders. In many tutorials the have a Scripts folder, but i don't cause creating an MVC project with VS put js file in 'wwwroot" so i thougth to use that folder to contains my Component.
Program.cs:
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.V8;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddRazorRuntimeCompilation();
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Index.js:
class Index extends React.Component {
render() {
return (
<h1> Hello Jems </h1>
)
}
}
ReactDOM.render(<Index />, document.getElementById("root"))
Index.cshtml
#using SportData.Web.Models;
#using React.Web.Mvc;
#model SportContainer
<div id="root"></div>
<script src="~/js/index.jsx"></script>
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - SportData</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/WebApplication1.styles.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/card.css" asp-append-version="true" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<script crossorigin="anonymous" src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin="anonymous" src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#await RenderSectionAsync("Scripts", required: false)
</body>
</html>
[link to directory foldes]
[1]: https://i.stack.imgur.com/VEQom.png

Changing the default page in BlazorWebAssembly not working

using Visual Studio 2019, I created a Blazor Web Assembly project.
I want to use the index.html page for something else, so I removed the <app></app> tag from it.
Then created another page named dashboard.html and added a dashboard.razor page. In this page added #page "/dashboard" and the <app></app> tag.
Now when I navigate to dashboard.html from index.html, am getting message "there is nothing at this address"
How could I make the dashboard.html page as my main app page?
Any ideas most appreciated.
This is how the project properties look:
To get this running I suggest you set up a blank WASM project from the Blazor template. Once you have it running you can make the necessary changes to your project. (My project is called Blazor.Starter.WASM.)
Move the Client project wwwroot to the Server project.
Copy index.html to dashboard.html - here's
serverproject/wwwroot/dashboard.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Blazor.Starter.WASM</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="Blazor.Starter.WASM.Client.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/site.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
My simple index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Blazor.Starter.WASM</title>
<base href="/"/>
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="m-4 p-4">
Go to Dashboard
</div>
</body>
</html>
Index.razor looks like this. Note the two page references
#page "/"
#page "/dashboard/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
#code {
}
Counter.razor and all other pages in the SPA - add #page "/dashboard/nnnnn"
#page "/counter"
#page "/dashboard/counter"
.....
NavMenu.razor looks like this (changes to the hrefs):
.....
<div class="#NavMenuCssClass" #onclick="ToggleNavMenu">
<ul class="nav flex-column">
<li class="nav-item px-3">
<NavLink class="nav-link" href="dashboard" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
</li>
<li class="nav-item px-3">
<NavLink class="nav-link" href="dashboard/counter">
<span class="oi oi-plus" aria-hidden="true"></span> Counter
</NavLink>
</li>
<li class="nav-item px-3">
<NavLink class="nav-link" href="dashboard/fetchdata">
<span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
</NavLink>
</li>
......
Finally update Startup.cs on the Server project.
....
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
// New section to map all requests starting with /dashboard to the Blazor Wasm project
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/dashboard"), app1 =>
{
app1.UseRouting();
app1.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("dashboard.html");
});
});
// default endpoint
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
}
If I have these instructions correct the application should start on the simple index page. Once in the WASM try an F5 to check the Endpoint mapping works correctly - note all #page references within the SPA must be prefixed with /dashboard to ensure the F5 reload works.

In dotnet core 3.0 RC1 is it possible to prerender a client-side Blazor app on the server?

I've read a few articles about doing this in earlier previews but none of them works for RC1.
What I'm trying to achieve is that the first request into the URL (regardless of if it's / or /about, etc.) should have the page content rendered by the server-side application and the full markup delivered to the browser.
Once that first request is done the client-side Blazor Web Assembly app should take over.
What I have right now:
LCBlazor.Client - the client-side Blazor app
LCBlazor.Server - a server-side dotNet core 3 app
// MyApp.Server - Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
services.AddServerSideBlazor();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
app.UseClientSideBlazorFiles<Client.Startup>();
app.UseFileServer();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapFallbackToPage("/_Host");
//endpoints.MapFallbackToClientSideBlazor<App>("/index.html");
});
}
#* LCBlazor.Server.Pages._Host.cshtml *#
#page "/"
#namespace LCBlazor.Server.Pages
#using LCBlazor.Client
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>LCBlazor Prerendered</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
</head>
<body>
<app>#(await Html.RenderComponentAsync<App>(RenderMode.Server))</app>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Everything else is as-per the default blazor templates (with the RenderTree errors fixed).
The current behaviour is that the app loads, but if I disable JS in my browser I get no content which indicates that the app is still relying on the client-side for rendering.

Post data to controller .net core

I have the following controller:
[Route("api/[controller]")]
[Authorize]
public class AuthenticationController : Controller
{
private readonly IAuthenticationService _authenticationService;
public AuthenticationController(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}
[AllowAnonymous]
[HttpPost]
public IActionResult Authenticate([FromBody] UserModel userParams)
{
var authenticate = _authenticationService.Authenticate(userParams.Username, userParams.Password);
return Ok("");
}
[HttpGet]
public IActionResult GetAll()
{
var users = "Greta";
return null;
}
}
I'm trying to make a post with postman, but I get this result:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/Authentication/Authenticate</pre>
</body>
</html>
Have anyone an idea why I get this error?
I'm using the React-template with Visual Studio. Can it have something to do with that?
When I try to access the GetAll endpoint, I get this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<base href="/" />
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json">
<link rel="shortcut icon" href="/favicon.ico">
<!--
Notice the use of in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>ICOM.Cbs</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script type="text/javascript" src="/static/js/bundle.js"></script>
</body>
</html>
EDIT: It seems to work now. I removed FromBody and then It worked. I also tried with FromForm, and It works. I don't know why.
I suspect you just need to explicitly specify the route for the action:
[AllowAnonymous]
[HttpPost(nameof(Authenticate))]
public IActionResult Authenticate([FromBody] UserModel userParams)
{
var authenticate = _authenticationService.Authenticate(userParams.Username, userParams.Password);
return Ok("");
}
Notice the route in the HttpPost attribute, which I just set to the name of the method.
If you just use .UseMvc() in your Startup.cs, then you aren't specifying default routes, so you need to specify the route for each action. If you want default routes to be automatically assigned, then you need to use this in your Startup.cs:
app.UseMvc(routes => {
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
But even if you do that, if you specify a Route at the controller level, the default routes go out the window, so you must specify the routes at each action in that controller.
More reading:
Routing in ASP.NET Core
Routing to controller actions in ASP.NET Core
When using [FromBody] only in your controller and you are testing with PostMan. Instead of using form-data use raw and choose prefered Content-Type: application/json

Static file not loading via wwwroot c#

Ok so I don't know what I am missing here. All I am trying to do is show that my static css file is linking to my index page. I have loaded the dependencies and have it in the startup.cs was hoping someone could tell me where Im messing it up. ALl this should do is turn the h1 in index green The page does load just fine just not changing the color.
Project.json
"dependencies": {
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
Startup.cs
public void Configure(IApplicationBuilder app, ILoggerFactory
loggerFactory)
{
// Use the Mvc to handle Http requests and responses
loggerFactory.AddConsole();
app.UseStaticFiles();
app.UseDeveloperExceptionPage();
app.UseMvc();
}
Index.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Index</title>
<link rel="stylesheet" href="~/css/style.css"/>
</head>
<body>
<div id = "test">
<h1>Hello ASP.NET Mvc!</h1>
</div>
</body>
</html>
Style.css
*{
margin: 0px;
padding: 0px;
}
h1{
color: green;
}
Structure of wwwroot
wwwroot
css
style.css
Read this to enable static content:
link

Categories