add Contorller

This commit is contained in:
SpringHgui 2020-11-01 00:07:31 +08:00
parent 68d256caf0
commit abacc6b0a0
18 changed files with 225 additions and 92 deletions

View File

@ -4,9 +4,9 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FastTunnel.Server namespace FastTunnel.Core.Config
{ {
public class Appsettings public class AppSettings
{ {
public DefaultServerConfig ServerSettings { get; set; } public DefaultServerConfig ServerSettings { get; set; }
} }

View File

@ -9,7 +9,7 @@ namespace FastTunnel.Core.Extensions
{ {
public static void LogError(this ILogger logger, Exception ex) public static void LogError(this ILogger logger, Exception ex)
{ {
logger.LogError(ex.ToString()); logger.LogError(ex, string.Empty);
} }
} }
} }

View File

@ -0,0 +1,16 @@
using FastTunnel.Core.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace FastTunnel.Core.Extensions
{
public static class ServicesExtensions
{
public static void AddFastTunnel(this IServiceCollection service)
{
service.AddTransient<IAuthenticationFilter, DefaultAuthenticationFilter>();
}
}
}

View File

@ -0,0 +1,16 @@
using FastTunnel.Core.Core;
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace FastTunnel.Core.Filters
{
public class DefaultAuthenticationFilter : IAuthenticationFilter
{
public virtual bool Authentication(FastTunnelServer server, LogInMassage requet)
{
return true;
}
}
}

View File

@ -1,33 +1,35 @@
using FastTunnel.Core.Config; using FastTunnel.Core.Config;
using FastTunnel.Core.Core; using FastTunnel.Core.Core;
using FastTunnel.Core.Filters;
using FastTunnel.Core.Global; using FastTunnel.Core.Global;
using FastTunnel.Server.Filters;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Runtime.ExceptionServices; using System.Runtime.ExceptionServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FastTunnel.Server.Service namespace FastTunnel.Core.Services
{ {
public class ServiceFastTunnelServer : IHostedService public class ServiceFastTunnelServer : IHostedService
{ {
ILogger<ServiceFastTunnelServer> _logger; ILogger<ServiceFastTunnelServer> _logger;
FastTunnelServer _fastTunnelServer; FastTunnelServer _fastTunnelServer;
TestAuthenticationFilter _testAuthenticationFilter; IAuthenticationFilter _authenticationFilter;
IConfiguration _configuration; IConfiguration _configuration;
public ServiceFastTunnelServer( public ServiceFastTunnelServer(
ILogger<ServiceFastTunnelServer> logger, ILogger<ServiceFastTunnelServer> logger,
IConfiguration configuration, IConfiguration configuration,
TestAuthenticationFilter testAuthenticationFilter) IAuthenticationFilter authenticationFilter)
{ {
_configuration = configuration; _configuration = configuration;
_testAuthenticationFilter = testAuthenticationFilter; _authenticationFilter = authenticationFilter;
_logger = logger; _logger = logger;
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
@ -50,10 +52,13 @@ namespace FastTunnel.Server.Service
private void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e) private void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{ {
if (e.Exception is System.IO.DirectoryNotFoundException) if (e.Exception is DirectoryNotFoundException)
{ {
// nlog第一次找不到文件的错误跳过 // nlog第一次找不到文件的错误跳过
} }
else if (e.Exception is IOException && e.Exception.Source == "System.Net.Security")
{
}
else else
{ {
_logger.LogError(e.Exception, "【FirstChanceException】"); _logger.LogError(e.Exception, "【FirstChanceException】");
@ -64,8 +69,8 @@ namespace FastTunnel.Server.Service
{ {
_logger.LogInformation("===== FastTunnel Server Starting ====="); _logger.LogInformation("===== FastTunnel Server Starting =====");
_fastTunnelServer = new FastTunnelServer(_logger, _configuration.Get<Appsettings>().ServerSettings); _fastTunnelServer = new FastTunnelServer(_logger, _configuration.Get<AppSettings>().ServerSettings);
FastTunnelGlobal.AddFilter(_testAuthenticationFilter); FastTunnelGlobal.AddFilter(_authenticationFilter);
try try
{ {

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div style="text-align:center;">Coming soon!</div>
</body>
</html>

View File

@ -4,13 +4,13 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace FastTunnel.Core.WebApi.Controllers namespace FastTunnel.Server.Controllers
{ {
public class HomeController : Controller public class HomeController : Controller
{ {
public string Index() public ViewResult Index()
{ {
return "ok"; return View();
} }
} }
} }

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace FastTunnel.Server.Controllers
{
public class OperateContoller : Controller
{
[Route("restart")]
public string Restart()
{
// TODO:Restart FastTunnel
return "FastTunnel Will Restart";
}
}
}

View File

@ -1,30 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<UserSecretsId>17e7d83b-9640-4fba-8e72-2b6b022a01b0</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.0" /> <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.0" /> </ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.0" /> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" /> <None Include="nlog.config">
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" /> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<PackageReference Include="NLog" Version="4.6.8" /> </None>
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" /> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.9" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.9" />
<PackageReference Include="NLog" Version="4.7.5" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FastTunnel.Core\FastTunnel.Core.csproj" /> <ProjectReference Include="..\FastTunnel.Core\FastTunnel.Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,41 +1,55 @@
using Microsoft.Extensions.DependencyInjection; using FastTunnel.Core.Extensions;
using NLog.Extensions.Logging; using FastTunnel.Core.Services;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using FastTunnel.Server.Service; using Microsoft.Extensions.DependencyInjection;
using FastTunnel.Core.Logger; using Microsoft.Extensions.Hosting;
using FastTunnel.Server.Filters; using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
namespace FastTunnel.Server namespace FastTunnel.Server
{ {
class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateHostBuilder(args).Build().Run(); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
} }
/// <summary>
/// 使用托管服务实现后台任务:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) Host.CreateDefaultBuilder(args)
.ConfigureLogging((context) =>
{
context.AddNLog(NlogConfig.getNewConfig());
})
.ConfigureServices((hostContext, services) => .ConfigureServices((hostContext, services) =>
{ {
// -------------------FastTunnel START------------------
services.AddFastTunnel();
services.AddHostedService<ServiceFastTunnelServer>(); services.AddHostedService<ServiceFastTunnelServer>();
// -------------------FastTunnel END--------------------
// DI })
services.AddTransient<TestAuthenticationFilter>(); .ConfigureWebHostDefaults(webBuilder =>
//services.AddSingleton<IServerConfig>();
}).ConfigureWebHostDefaults(webBuilder =>
{ {
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();
}); })
// NLog
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection
} }
} }

View File

@ -1,16 +1,18 @@
{ {
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:5249", "applicationUrl": "http://localhost:60256",
"sslPort": 0 "sslPort": 44335
} }
}, },
"profiles": { "profiles": {
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
@ -18,13 +20,11 @@
"FastTunnel.Server": { "FastTunnel.Server": {
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
}, }
"applicationUrl": "https://localhost:5001;http://localhost:5000"
},
"Docker": {
"commandName": "Docker"
} }
} }
} }

View File

@ -1,46 +1,52 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using FastTunnel.Core.Filters;
using FastTunnel.Server.Filters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace FastTunnel.Server namespace FastTunnel.Server
{ {
public class Startup public class Startup
{ {
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration)
{ {
Configuration = configuration; Configuration = configuration;
} }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllersWithViews(); services.AddControllersWithViews();
// ------------------------Custom Business------------------------------
services.AddTransient<IAuthenticationFilter, TestAuthenticationFilter>();
} }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) // 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()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
else
{
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.UseHttpsRedirection();
app.UseHsts();
}
app.UseRouting(); app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllerRoute( endpoints.MapControllerRoute(
@ -49,4 +55,4 @@ namespace FastTunnel.Server
}); });
} }
} }
} }

View File

@ -0,0 +1,6 @@
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<div style="text-align:center;padding:50px;">Soming soon!</div>

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -1,31 +1,33 @@
{ {
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", // Information // Trace Debug Information Warning Error
"Microsoft": "Error", "Default": "Trace",
"Microsoft.Hosting.Lifetime": "Error" "Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
} }
}, },
"AllowedHosts": "*",
"ServerSettings": { "ServerSettings": {
// //
"BindAddr": "0.0.0.0", "BindAddr": "0.0.0.0",
// //
"BindPort": 1271, "BindPort": 1271,
// web穿 // web穿
"WebDomain": "test.cc", "WebDomain": "test.cc",
// , 访url http://{SubDomain}.{Domain}:{ProxyPort_HTTP}/ // , 访url http://{SubDomain}.{Domain}:{ProxyPort_HTTP}/
// web穿 // web穿
"WebProxyPort": 1270, "WebProxyPort": 1270,
// ngixn访 // ngixn访
"WebHasNginxProxy": false, "WebHasNginxProxy": false,
// 访ip // 访ip
"WebAllowAccessIps": [], "WebAllowAccessIps": [],
// SSHSSH.false // SSHSSH.false
"SSHEnabled": true "SSHEnabled": true
} }
} }

View File

@ -0,0 +1,26 @@
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="File" name="file"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="${basedir}/Logs/${shortdate}.${level}.log" />
<target xsi:type="Console" name="console"
layout="${date}|${level:uppercase=true}|${message} ${exception}" />
<!--layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />-->
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file,console" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
</rules>
</nlog>

View File

@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "杂项", "杂项", "{6B8745
Dockerfile = Dockerfile Dockerfile = Dockerfile
EndProjectSection EndProjectSection
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{0E2A9DA2-26AE-4657-B4C5-3A913E2F5A3C}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -36,6 +38,9 @@ Global
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C8ADFEB1-59DB-4CE3-8D04-5B547107BCCB} = {0E2A9DA2-26AE-4657-B4C5-3A913E2F5A3C}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3D9C6B44-6706-4EE8-9043-802BBE474A2E} SolutionGuid = {3D9C6B44-6706-4EE8-9043-802BBE474A2E}
EndGlobalSection EndGlobalSection