最佳答案
Azure 的错误是:
. Net Core: 应用程序启动异常: FileNotFoundException: 配置文件 没有找到“ appsetings.json”,也不是可选的。
所以这有点模糊。我似乎无法确定。我正试图部署一个。Net Core Web API 项目到 Azure,我得到了这个错误:
: (糟糕。500内部服务器错误 启动应用程序时出错。
我已经部署好了。网络应用程序接口,它们已经工作了。我关注了一些在线教程,它们很有效。但不知怎么的,我的项目破产了。在 Web.config 上启用 stdoutLogEnable 并查看 Azure 流日志可以得到以下结果:
2016-08-26T02:55:12 Welcome, you are now connected to log-streaming service.
Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Quanta.API.Startup..ctor(IHostingEnvironment env) in D:\Source\Workspaces\Quanta\src\Quanta.API\Startup.cs:line 50
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider services, Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:30261
Application started. Press Ctrl+C to shut down.
好吧,看起来很简单。它找不到应用程序 json。看看我的配置(startup.cs) ,它似乎定义得非常好。我的初创公司是这样的:
public class Startup
{
private static string _applicationPath = string.Empty;
private static string _contentRootPath = string.Empty;
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
_applicationPath = env.WebRootPath;
_contentRootPath = env.ContentRootPath;
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(_contentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return System.IO.Path.Combine(app.ApplicationBasePath, "Quanta.API.xml");
}
// 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)
{
var pathToDoc = GetXmlCommentsPath();
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"],
b => b.MigrationsAssembly("Quanta.API")));
//Swagger
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Project Quanta API",
Description = "Quant.API",
TermsOfService = "None"
});
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
// Repositories
services.AddScoped<ICheckListRepository, CheckListRepository>();
services.AddScoped<ICheckListItemRepository, CheckListItemRepository>();
services.AddScoped<IClientRepository, ClientRepository>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddScoped<IDocumentTypeRepository, DocumentTypeRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IProtocolRepository, ProtocolRepository>();
services.AddScoped<IReviewRecordRepository, ReviewRecordRepository>();
services.AddScoped<IReviewSetRepository, ReviewSetRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
// Automapper Configuration
AutoMapperConfiguration.Configure();
// Enable Cors
services.AddCors();
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
// Force Camel Case to JSON
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
// Uncomment the following line to add a route for porting Web API 2 controllers.
//routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
//Ensure DB is created, and latest migration applied. Then seed.
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
QuantaContext dbContext = serviceScope.ServiceProvider.GetService<QuantaContext>();
dbContext.Database.Migrate();
QuantaDbInitializer.Initialize(dbContext);
}
app.UseSwagger();
app.UseSwaggerUi();
}
}
这在当地很管用。但一旦我们发布到 Azure 上,就失败了。我不知所措。我创造了新的。部署到 Azure 的 Net 核心项目刚刚发现。但是这个我投入了所有时间的项目似乎失败了。我已经准备好复制和粘贴失败的项目的代码到一个新的项目中,但我真的很好奇是什么破坏了这一点。
有什么想法吗?
编辑: 所以我的程序是:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Quanta.API
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
编辑2: 根据 Frans 的说法,我查了出版物的选项,是:
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
我从一个工作项目中提取了一个出版物选项,并将其更改为:
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/Views",
"appsettings.json",
"web.config"
]
},
它仍然给出了一个500错误,但是没有给出堆栈跟踪,说明它可以加载 appsettings.json。现在它正在抱怨与 SQL 的连接。我注意到我的 SQL 连接字符串代码在很多 RC1博客文章中都有提到。的 RC2。网络核心改变了它。所以我更新到:
"Data": {
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=QuantaDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
然后把我的创业公司改成:
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Quanta.API")));
终于成功了。
我必须遵循一个较老的 RC1例子,并没有意识到这一点。