.AddRazorRuntimeCompilation() results in The type or namespace name 'IWebHostEnvironment' could not be found - asp.net-core

In a .NET 6 / ASP.NET Core app after adding the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget package and adding
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
I get this error, when opening a view:
The type or namespace name 'IWebHostEnvironment' could not be found (are you missing a using directive or an assembly reference?)
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n</html>\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public IWebHostEnvironment HostingEnv { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
IWebHostEnvironment is referenced in _Layout.cshtml:
#inject IWebHostEnvironment HostingEnv
<!DOCTYPE html>
<html lang="en">
...
</html>
Note:
The accepted answer works, however, Rider (and maybe ReSharper) might mark Microsoft.AspNetCore.Hosting. in the #inject statement as redundant.
I don't know why this happens, but I added this above the #inject statement line:
#* ReSharper disable once RedundantNameQualifier *#
Also, read my comment regarding the IsDevelopment() error I got after using the full qualified reference.

Have you tried fully qualifying the namespace and making it
#inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnv
If that works then I recall there being a difference in how _ViewImports files are processed during runtime compilation versus standard, it doesn’t cascade the same way. You may therefore find that your existing _ViewImports files aren’t all being read.

Related

Namespace name 'IndexModel' could not be found while running Entity Framework Core tutorial in ASP.NET Core

I am trying to follow this tutorial from Microsoft:
Razor Pages with Entity Framework Core in ASP.NET Core - Tutorial 1 of 8:
[https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-5.0&tabs=visual-studio]
I created the project correctly, but i can't run the project because when i replace the copied code from this step in tutorial "Set up the site style" in my project: Views/Home/Index.cshtml and I try to run is showing me:
The type or namespace name 'IndexModel' could not be found...
The problem seems to be here:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
Where is this model I can't find it, I just created the application, and the model does not exist? Or I pasted in the wrong file because in tutorial is saying: "Pages/Index.cshtml, replace the contents of the file with the following code:" I can't find neither "Pages" folder?
Apparently the screenshot on the page is misleading, because there is a selected MVC project while this tutorial needs to work in a "Web app" without MVC. I didn't see a point above where it says to select "Web app" without MVC, the mistake was mine but the picture is also misleading. I believe many people have slipped into this mistake.
The screenshot
In your sample project, you should have:
Index.cshtml
Index.cshtml.cs
The Index.cshtml.cs might appear nested under Index.cshtml (so expand that).
Check that the Index.cshtml.cs includes something like this:
namespace ContosoUniversity.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
You can see that this is where your IndexModel is declared.
Did you rename the page Index.cshtml? Did you rename or delete Index.cshtml.cs?
The .cs is called "code behind" because its the code that supports the .cshtml file.

M-V-C Fool-proof not working and showing Uncaught error?

I installed Fool-Proof from nuGet, but its not working uncaught errors.
Install-Package foolproof -Version 0.9.4518
As I installed it, new folder with name Clients Scripts gets added in to my project with three libraries: FoolProof Unobtrusive, FoolProof jQuery Validation and FoolProof Validation. Then I create new bundle in bundle.config and linked with my shared layout.
public bool active { get; set; }
[RequiredIf("active", true,ErrorMessage = "Code is Required")]
public int Code { get; set; }
It's not displaying validation message. Now, when I checked my console I am getting following errors:
You haven't loaded required js files. Add the following in BundleConfig.js
bundles.Add(new ScriptBundle("~/bundles/mvcfoolproof").Include(
"~/Scripts/MicrosoftAjax.js",
"~/Scripts/MicrosoftMvcAjax.js",
"~/Scripts/MicrosoftMvcValidation.js",
"~/Client Scripts/mvcfoolproof.unobtrusive.min.js",
"~/Client Scripts/MvcFoolproofJQueryValidation.min.js",
"~/Client Scripts/MvcFoolproofValidation.min.js"));
and then include in your View in correct order
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/mvcfoolproof")

How to get compile time errors in views using ASP.NET CORE

How can we get compile time errors in views and view components in Mvc6?
In MVC 5, it was simple to edit the .csproj file. How do we do it now?
Answer for RC-1
Create the following RazorPreCompilation class:
namespace YourApp.Compiler.Preprocess
{
public sealed class RazorPreCompilation : RazorPreCompileModule
{
protected override bool EnablePreCompilation(BeforeCompileContext context) => true;
}
}
Places this class in {root}/Compiler/Preprocess.
Add a call to AddPrecompiledRazorViews in your ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
// ... other code ...
services
.AddMvc()
.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
// ... other code ...
}
As noted in other answers, when views are precompiled you lose the ability to change them while the application is running. Additionally, it seems that sometimes you have to do a rebuild on your project (as opposed to just a build) in order for new code changes to take effect. For example, correcting a typo in a Razor method call may still trigger a compilation error until you rebuild the project.
Update on Directives
If you'd like to have this run with preprocess directives, wrap them around the AddPrecompiledRazorViews call like this:
public void ConfigureServices(IServiceCollection services)
{
// ... other code ...
var mvcBuilder = services.AddMvc()
#if !DEBUG
mvcBuilder.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
#endif
// ... other code ...
}
You can use pre-compiled views by adding the following class to your project. However, doing this stops you from being able to edit the views at runtime. Therefore, I have added the #if !DEBUG pre-processor directive so that the views are only pre-compiled in release mode.
#if !DEBUG
namespace MvcBoilerplate.Compiler.Preprocess
{
using System;
using Microsoft.AspNet.Mvc;
/// <summary>
/// Enable pre-compilation of Razor views, so that errors in your .cshtml files are caught and displayed
/// in the Visual Studio errors window at compile time, rather than your sites users receiving a runtime 500
/// internal server error. Pre-compilation may reduce the time it takes to build and launch your project but will
/// cause the build time to increase. It will also stop edit and continue working for .cshtml files.
/// </summary>
public class RazorPreCompilation : RazorPreCompileModule
{
}
}
#endif
Secondly, in Startup.cs you need to actually use the pre-compiled views which you can do like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
}
Pre-compiled views give quicker application startup performance.
You must add a class
public class RazorPreCompilation : RazorPreCompileModule
{
public RazorPreCompilation(IServiceProvider provider) : base(provider)
{
this.GenerateSymbols = true;
}
}
and Add AddPrecompiledRazorViews to your mvc setup in your startup class
see this question

MVC SQL No Connection String Named Could Be Found in the Application Config File EF6

I have searched through a number of questions(No Connection String Named MyEntities Could Be Found In The Application Config), but most seem to deal with multiple projects in a solution, in this case I have only one project in one solution. Also this is my first MVC Project with EF6. When going to add a controller I get this error:
This is my Web.Config
And This is My Solution Explorer
I know the error references an Application Config File, but I do not have an app Config file, nor do I know where to put it or how to create it.
EDIT, Here is the code for the db context
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("name=DBConnection"){}
public System.Data.Entity.DbSet<zzz.Models.Supplier> Suppliers { get; set; }
}

How to inject repositories into a custom MembershipProvider?

It seem i can't get this to work. I made a custom MembershipProvider and i want to inject a repository inside but the [Inject] property just doesnt work.
public class PyrosphereMembershipProvider : MembershipProvider
{
[Inject]
protected IDepositoireUtilisateur DepositoireUtilisateur { get; set; }
[Inject]
protected IDepositoireProfile DepositoireProfile { get; set; }
...
I think this is because this class are created way before the MVC application is running which cause the actual problem. I am getting more problem trying to use the membershipprovider than making my own system.
About my ninject configuration i am using the App_Start directory method. All my binding are correct ive looked so that nothing to do with my bindings.
Any help is appreciated!
The ASP.NET Providers aren't designed for proper dependency injection. There are only workarounds for them.
Either you have to setup a binding for them and resolve atleast one instance before using them. E.g. by injecting an instance into the Global.asax or you have to Inject an instance manually before the first use (kernel.Inject(...)). Again most likely in the global.asax application start method.