UseStaticFiles() throws error "Connection refused" - asp.net-core

I have problem with serving static file in asp.net core. I am really new to it. Just followed a tutorial from pluralsight and stuck here.
I have added index.html in wwwroot folder, and added dependencies for static file in Json, but still does not seems to work. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace TheWorld
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
// app.Run(async (context) =>
// {
// await context.Response.WriteAsync("Hello World!");
// });
}
}
}
And this is my project.json
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}

In order for your Web app to serve a default page without the user having to fully qualify the URI, call the UseDefaultFiles extension method from Startup.Configure as follows.
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
UseDefaultFiles must be called before UseStaticFiles to serve the default file.
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#serving-default-files

Related

Asp.net Core EF options.UseInMemoryDatabase System.TypeLoadException

I used EF in Asp.net Core, but got below error in below code:
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
}
public DbSet<TodoItem> TodoItems { get; set; }
}
Error Message:
An exception of type 'System.TypeLoadException' occurred in
Microsoft.EntityFrameworkCore.dll but was not handled in user code
Additional information: Could not load type
'Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionExtensions'
from assembly 'Microsoft.Extensions.DependencyInjection.Abstractions,
Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
Here is my Project.json
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Logging.Console": "1.0.0",
//Dependence for MVC
"Microsoft.AspNetCore.Mvc": "1.1.1",
"Microsoft.AspNetCore.StaticFiles": "1.1.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
"Microsoft.Extensions.Configuration.Json": "1.1.0",
//Dependence for EF
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.InMemory": "1.0.0-rc2-final"
//Dependence for EF with SQL, this is avalible under VS 2017 RC
//"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
//Entity Framework commands to maintain the database
//"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview4-final"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
//used for Razor pages which are compiled at runtime,and the compiler needs access to reference assemblies,
//to make sure it compiles correctly
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Any help would be appreciated.
Reards,
Edward
After trying, I changed "1.0.0-rc2-final" to "1.1.0" which I already have tried, but I found there is an warning, "Dependency conflict. CoreMVCWebAPI 1.0.0 expected Microsoft.EntityFrameworkCore.InMemory >= 1.1.0 but received 1.0.0-rc2-final", after install this package manually instead of only changing project.json, it works now.
Install-Package Microsoft.EntityFrameworkCore.InMemory
I just wanted to add that I had to restart VS2017 before the package restore was recognised. Prior to that I was getting an error
DbContextOptionsBuilder does not contain a definition for
UseInMemoryDatabase() ...
I hope this saves you time.

FluentValidation.AspNetCore is not working in Class Library

I am using library "FluentValidation.AspNetCore": "6.4.0-beta3" in .netcore WebApi in a project. You can see the project structure below. Library is working fine if i place the CurrencyDTO.cscode in section 2 (Project FH.WebAPI) and if the same code placed in section 1 (Class Library DTO) its not working. And requirement is that i have to place code in Class library FH.Common. Is there any work around.I have search but didn't find any thing
Project Structure
CurrencyDTO.cs
[Validator(typeof(CurrencyDTOValidator))]
public class CurrencyDTO
{
public int Id { get { return CurrencyId; } }
public int CurrencyId { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
public class CurrencyDTOValidator : AbstractValidator<CurrencyDTO>
{
public CurrencyDTOValidator()
{
RuleFor(x => x.Name).NotEmpty().NotNull().WithMessage("The currency 'Name' is required.")
.Length(0, 250).WithMessage("The currency 'Name' cannot be more than 250 characters.");
RuleFor(x => x.Symbol).NotEmpty().WithMessage("The currency Symbol is required.");
}
}
Library Configuration
Step 1) . Add in project.json
{
"dependencies": {
"Autofac": "4.3.0",
"Autofac.Extensions.DependencyInjection": "4.0.0",
"AutoMapper": "5.2.0",
"EntityFramework": "6.1.3",
"FH.Business": "1.0.0-*",
"FH.Common": "1.0.0-*",
"JWT": "1.4.1-beta",
"Microsoft.AspNet.Http.Extensions": "1.0.0-rc1-final",
"Microsoft.AspNet.WebApi.Client": "5.2.3",
"Microsoft.AspNet.WebApi.Core": "5.2.3",
"Microsoft.AspNetCore.Authentication.JwtBearer": "1.1.0",
"Microsoft.AspNetCore.Diagnostics": "1.1.0",
"Microsoft.AspNetCore.Mvc": "1.1.1",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
//other libraries..
"FluentValidation.AspNetCore": "6.4.0-beta3" //<------Here
},
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"net461": {
"frameworkAssemblies": {
"System.Drawing": "4.0.0.0"
}
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"prepublish": [ "bower install", "dotnet bundle" ],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Step 2). In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options => { }).AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
// Other code..
}
Used in Controller
[HttpPost]
[Route("CreateCurrency")]
public IActionResult CreateCurrency([FromBody] CurrencyDTO model)
{
if (!ModelState.IsValid) //<----Validate here
{
return new BadRequestObjectResult(ModelState);
}
//Other Code..
}
The problem was in a registration line in startup.csand thank to #JeremySkinner who have suggested me the right way and i am quoting his answer here.
My mistake
services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
Replace
RegisterValidatorsFromAssemblyContaining<Startup>()
with
RegisterValidatorsFromAssemblyContaining<CurrencyDTOValidator>()
Actual link to the Issue
Link Description
Above link is the answers posted #JeremySkinner

AspNetCore not getting POST data initially in framework 4.6.2

I've just updated my Azure Web App from aspnetcore rc2 to aspnetcore 1.0, .net framework 4.6.2 and preview 2 tooling. Since this change I've had an issue where for the first minute or so after deploy my controller is not getting any POST data. The object that should contain it is always null. After a minute or so the code begins to work as expected.
Response time to the first web call seems much faster now, making me suspect that my app is being sent requests before the app is fully initialised. This does not happen locally, only when deployed to Azure.
Is there anything I need to do to ensure that the app is fully initialised before it starts to receive requests?
If I try to access this.HttpContext.Request.Body directly then it throws
Cannot access a disposed object. Object name: 'FileBufferingReadStream'.
My project.json looks like this in case it's relevant:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"runtimeOptions": {
"gcServer": true
},
"dependencies": {
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.AspNetCore.Hosting": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Newtonsoft.Json": "9.0.1"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview2-final",
"imports": "portable-net45+win8+dnxcore50"
}
},
"frameworks": {
"net462": {
}
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"appsettings.json",
"web.config"
]
},
"userSecretsId": "redacted",
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
The code for the controller is pretty simple. In the first minute or so this will return badrequest, after that the same request will return Ok.
[HttpPost]
[Produces( "application/json" )]
public IActionResult Post( [FromBody] MyRequestDataClass RequestData )
{
if (RequestData == null)
{
return BadRequest();
}
return Ok();
}

Reference a NET461 DLL model type from ASP.NET Core View

I have a new ASP.NET Core RC2 built as follows:
Model stored in DLL library of .NET Framework 461
Web is MVC Core 1.0 Full Framework - not based on core framework
when reference the model type in the DLL library and run the project, i got the following error:
An error occurred during the compilation of a resource required to
process this request. Please review the following specific error
details and modify your source code appropriately. Generated Code The
type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
23. public class _Views_Murad_Index_cshtml : Microsoft.AspNetCore.Mvc.Razor.RazorPage>
The type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
39. public Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper>
Html { get; private set; } An error occurred during the compilation of
a resource required to process this request. Please review the
following specific error details and modify your source code
appropriately. Generated Code The type or namespace name 'Data' does
not exist in the namespace 'ADMA.EWRS' (are you missing an assembly
reference?)
23. public class _Views_Murad_Index_cshtml : Microsoft.AspNetCore.Mvc.Razor.RazorPage>
The type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
39. public Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper>
Html { get; private set; }
Config Project.json as follow :
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview1-final",
"type": "build"
},
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
"Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
"Microsoft.AspNetCore.Authorization": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Authentication": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Session": "1.0.0-rc2-final",
"ADMA.EWRS.Web.Security": "1.0.0-*"
},
"tools": {
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
},
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
}
},
"frameworks": {
"net461": {
"dependencies": {
"ADMA.EWRS.BizDomain": {
"target": "project"
},
"ADMA.EWRS.Data.Models": {
"target": "project"
}
}
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"appsettings.json",
"web.config"
]
},
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Solution Explorer
X Project
Solved after Adding Razor Options as in below code :
services.AddMvc().// Murad Add this for RC2, remove it if release 1.0 after June
AddRazorOptions(options =>
{
var previous = options.CompilationCallback;
options.CompilationCallback = context =>
{
previous?.Invoke(context);
context.Compilation = context.Compilation.AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ADMA.EWRS.Data.Models.Murad).Assembly.Location));
};
});
//var myAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(x => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(x.Location)).ToList();
//services.Configure((Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions options) =>
//{
// var previous = options.CompilationCallback;
// options.CompilationCallback = (context) =>
// {
// previous?.Invoke(context);
// context.Compilation = context.Compilation.AddReferences(myAssemblies);
// };
//});
Check
https://github.com/aspnet/Mvc/issues/4686

Getting blank pages for error messages with UseDeveloperExceptionPage enabled

I'm getting blank pages for both when I enter an invalid URL, or when an exception is thrown within my application. I have UseDeveloperExceptionPage() enabled, and I have confirmed that my app environment is in development mode, and that the method is firing. The app works fine, but not having error messages displaying in the browser is frustrating.
My Startup.cs Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(m =>
m.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
));
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
CreateSampleData(app.ApplicationServices).Wait();
}
My project.json
{
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
"Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
]
}
The order matters - put UseMvc(..) after your exception blocks so the exception middleware can catch exceptions that the Mvc middleware throws.
If you take a look at the source for DeveloperExceptionPageMiddleware you can see that it simply calls the next middleware in the pipeline inside a try/catch.
404s however will still show a blank page, as they are not an exception. To configure something else for those, take a look at StatusCodeErrorPages.