Getting blank pages for error messages with UseDeveloperExceptionPage enabled - asp.net-core

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.

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

UseStaticFiles() throws error "Connection refused"

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

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();
}

Use local class library as resource for Web API (ASP.NET Core 1.0)

I'm stuck with very simple problem.
I want to load local .NET 4 class library (dll) project to be used as resource in my new ASP.NET Web API project (first time trying asp.net)
I'm familiar with Winforms apps and now trying to create a ASP.NET Web API to be able to access one of my helper DLL from PHP/linux server. I'm not sure if this is a good approach, but I'm trying to prevent from re-implementing the logic of the DLL in PHP code.
The problem now is that I'm not able to add the DLL or the library class project to the resources of the Web API project.
While trying to solve the problem i have tried:
Visual Studio 2015 new project->ASP.NET web application->ASP.NET Core 1.0
templates->Web API
Create new Class Library project to the Web API solution (or import existing project)
Add the project to Web API project references
Add using directive of class library namespace to controller
Try to build and it gets error:
Error CS0246 The type or namespace name 'ClassLibrary1' could not be found (are you missing a using directive or an assembly reference?) WebApplication1.DNX Core 5.0
For me it it seems that it's trying to fetch the resource from nuget or something.
I hope some one can easily point me my mistake so I can continue to work with the actual work. (Or am I just miss using the Web API concept?)
project.json
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
},
"frameworks": {
"dnx451": {
"dependencies": {
"ClassLibraryTest2": "1.0.0-*"
}
},
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
]
}
No need to remove the dnxcore50 part.
Just remove "ClassLibraryTest2": "1.0.0-*" from dnx451 and add the dependency in the list of global dependencies. It will apply it on dnx451 and dnxcore50.
The project.json would look like this:
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"ClassLibraryTest2": "1.0.0-*"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
},
"frameworks": {
"dnx451": {
"dependencies": {
}
},
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
]
}