.ForMember(d => d.UsersCount, map => map.MapFrom((s,d) => s.Users?.Count ?? 0))
GetCurrentDirectory returns the worker directory of the process started by IIS rather than the app's directory (for example, C:\Windows\System32\inetsrv for w3wp.exe).html
which means config loader will not be able to find appsettings.*
files, or any other files such as custom config files, that depend on a GetCurrentDirectory
call. In order to solve it in your Program.cs right after public static void Main(string[] args) {
add the following linelinux
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
https://docs.microsoft.com/en-us/aspnet/core/migration/21-to-22?view=aspnetcore-2.2&tabs=visual-studio#call-configurekestrel-instead-of-usekestrelgit
https://devblogs.microsoft.com/aspnet/asp-net-core-2-2-0-preview2-now-available/github
https://www.cnblogs.com/stulzq/p/10069412.htmlweb
var path = Directory.GetCurrentDirectory();redis
dotnet tool install --global dotnet-dump --version 3.0.47001
https://garywoodfine.com/ihost-net-core-console-applications/mongodb
<aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="InProcess"> <handlerSettings> <handlerSetting name="debugFile" value="aspnetcore-debug.log" /> <handlerSetting name="debugLevel" value="FILE,TRACE" /> </handlerSettings> </aspNetCore>shell
<aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="InProcess"> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> <environmentVariable name="CONFIG_DIR" value="f:\application_config" /> </environmentVariables> </aspNetCore>緩存
eventvwr.msc安全
主動設置一下當前目錄爲程序根目錄:
System.IO.Directory.SetCurrentDirectory(hostingEnvironment.ContentRootPath);
<?xml version="1.0" encoding="utf-8"?> <configuration> <location path="." inheritInChildApplications="false"> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" /> </system.webServer> </location> </configuration>
如下 web.config 發佈用於獨立部署:
<PropertyGroup> <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> </PropertyGroup>
<?xml version="1.0" encoding="utf-8"?> <configuration> <location path="." inheritInChildApplications="false"> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath=".\MyApp.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" /> </system.webServer> </location> </configuration>
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
Try changing the section in csproj
<PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> </PropertyGroup>
to the following ...
<PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName> </PropertyGroup>
var rand = new Random(1);
var s = Stopwatch.StartNew();
for (var i = 0; i < Count; i++)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
try
{
reader.City(ip);
}
catch (AddressNotFoundException) { }
}
s.Stop();
Console.WriteLine("{0:N0} queries per second", Count / s.Elapsed.TotalSeconds);
RepositoryContext
https://code-maze.com/net-core-web-development-part4/
petapoco
https://blog.csdn.net/weixin_42930928/article/details/89513174
var service = (IFooService)serviceProvider.GetService(typeof(IFooService));
var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
配置
https://medium.com/@kritner/net-core-console-application-ioptions-t-configuration-ae74bfafe1c5
https://stackoverflow.com/questions/38114761/asp-net-core-configuration-for-net-core-console-application
string url1 = UriHelper.GetEncodedPathAndQuery(HttpContext.Request);
string baseUrl = string.Format("{0}://{1}{2}", Request.Scheme, Request.Host, Request.PathBase);
//redirect to register page
string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetEncodedPathAndQuery(context.HttpContext.Request);
if (url!=null && url.StartsWith("/"))
{
url = url.Substring(1);
}
context.Result = new RedirectToActionResult("login", "account", new { ReturnUrl = url});
public static string AppBaseUrl => $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}";
var displayUrl = UriHelper.GetDisplayUrl(Request);
https://sensibledev.com/how-to-get-the-base-url-in-asp-net/
[HttpGet]
public ActionResult<OrderDto> MapperTest()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Order, OrderDto>();
});
var order = new Order { Name="1"};
var mapper = config.CreateMapper();
OrderDto dto = mapper.Map<Order, OrderDto>(order);
return dto;
}
using StackExchange.Redis;
using System;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp26
{
class Program
{
const string MachineName = "redis-1cea240c-marc-3007", Password = "erdapkni51kql2uj";
const int Port = 10205;
static void Main()
{
const string Host = MachineName + ".aivencloud.com";
Console.WriteLine("connecting...");
var config = new ConfigurationOptions
{
EndPoints = { { Host, Port } },
Ssl = true, // enable TLS
Password = Password, // "AUTH" password
SslHost = Host, // check the host matches
};
config.CertificateValidation += CheckServerCertificate;
using (var conn = ConnectionMultiplexer.Connect(config))
{
Console.WriteLine("connected");
var db = conn.GetDatabase();
db.StringSet("hello", "world");
Console.WriteLine(db.StringGet("hello")); // writes: world
}
}
private static bool CheckServerCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// the lazy version here is:
// return true;
// better version - check that the CA thumbprint is in the chain
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
{
// check that the untrusted ca is in the chain
var ca = new X509Certificate2("ca.pem");
var caFound = chain.ChainElements
.Cast<X509ChainElement>()
.Any(x => x.Certificate.Thumbprint == ca.Thumbprint);
// note you could also hard-code the expected CA thumbprint,
// but pretty easy to load it from the pem file that aiven provide
return caFound;
}
return false;
}
}
}
Solution is to have a static reference to the LoggerFactory in a utility static class initialized on startup:
/// <summary> /// Shared logger /// </summary> internal static class ApplicationLogging { internal static ILoggerFactory LoggerFactory { get; set; }// = new LoggerFactory(); internal static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>(); internal static ILogger CreateLogger(string categoryName) => LoggerFactory.CreateLogger(categoryName); }
Which you intialize on Startup.cs:
public Startup(ILogger<Startup> logger, ILoggerFactory logFactory, IHostingEnvironment hostingEnvironment) { _log = logger; _hostingEnvironment = hostingEnvironment; Util.ApplicationLogging.LoggerFactory = logFactory;//<===HERE }
Then you can build a logger to use from your static class like so:
internal static class CoreJobSweeper { private static ILogger log = Util.ApplicationLogging.CreateLogger("CoreJobSweeper");
[Obsolete("Switch to the instance based API, preferably using dependency injection. See http://docs.automapper.org/en/latest/Static-and-Instance-API.html and http://docs.automapper.org/en/latest/Dependency-injection.html.")]
https://github.com/AutoMapper/AutoMapper/issues/3113
http://docs.automapper.org/en/stable/Dependency-injection.html
http://docs.automapper.org/en/latest/Dependency-injection.html
COMPlus_ThreadPool_ForceMinWorkerThreads=250
petapoco注入:
https://blog.csdn.net/weixin_42930928/article/details/89513174
.ForMember(d => d.UsersCount, map => map.MapFrom((s,d) => s.Users?.Count ?? 0))
Mapper.CreateMap<Source, Dest>() .ForMember(d => d.Foo, opt => opt.ResolveUsing(res => res.Context.Options.Items["Foo"]));
Mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");
<LangVersion>latest</LangVersion>
https://blog.csdn.net/sundna/article/details/92701805
https://garywoodfine.com/ihost-net-core-console-applications/
curl -X POST -d '{"text":"測試測試"}' url
public static string ReadFileContent(string filePath)
{
if (File.Exists(filePath))
{
using (var reader = new StreamReader(filePath))
{
var content = reader.ReadToEnd();
return content;
}
}
else
{
return "";
}
}
public static byte[] StreamToBytes(this Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
var a = Configuration.GetValue<int>(
"AppIdentitySettings:Password:RequiredLength");
var a = Configuration.GetValue<int>(
"AppIdentitySettings:Password:RequiredLength");
You probably mean: (k, v) => { v.Add(number); return v; }
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
private static Uri GetUri(HttpRequest request) { var builder = new UriBuilder(); builder.Scheme = request.Scheme; builder.Host = request.Host.Value; builder.Path = request.Path; builder.Query = request.QueryString.ToUriComponent(); return builder.Uri; }
var url = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
public static class Context { private static IHttpContextAccessor HttpContextAccessor; public static void Configure(IHttpContextAccessor httpContextAccessor) { HttpContextAccessor = httpContextAccessor; } private static Uri GetAbsoluteUri() { var request = HttpContextAccessor.HttpContext.Request; UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = request.Scheme; uriBuilder.Host = request.Host.Host; uriBuilder.Path = request.Path.ToString(); uriBuilder.Query = request.QueryString.ToString(); return uriBuilder.Uri; } // Similar methods for Url/AbsolutePath which internally call GetAbsoluteUri public static string GetAbsoluteUrl() { } public static string GetAbsolutePath() { } }
string referer = Request.Headers["Referer"].ToString();
Request.Headers["Referer"]
services.AddStackExchangeRedisCache(options => { options.Configuration = "127.0.0.1:6380,DefaultDatabase=1"; });
using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;
public Startup(IConfiguration 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)
{
//-----------redis分佈式緩存相關------------------
//services.AddMvc();
var redisConnection = Configuration.GetValue("redis:host");// Configuration.GetConnectionString("RedisConnection");
services.AddDataProtection()
.SetApplicationName("WebAppDotNetCore22")
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnection), "DataProtection-Keys");
services.AddStackExchangeRedisCache(o =>
{
o.Configuration = redisConnection;
});
services.AddSession(o =>
{
o.Cookie.Name = "WebAppDotNetCore22.Session";//設置一個cookie名,session要使用cookie
o.Cookie.SameSite = SameSiteMode.None;
o.Cookie.HttpOnly = true;//只能從http端獲取,增長安全性
o.IdleTimeout = TimeSpan.FromMinutes(10);
});
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//-----------redis分佈式緩存相關------------------
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
AddDistributedRedisCache
AddStackExchangeRedisCache
//初始化 RedisHelper RedisHelper.Initialization(csredis); //註冊mvc分佈式緩存 services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
private static Type[] GetAllChildClass(Type baseType)
{
var types = AppDomain.CurrentDomain.GetAssemblies()
//取得實現了某個接口的類
//.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ISecurity)))) .ToArray();
//取得繼承了某個類的全部子類
.SelectMany(a => a.GetTypes().Where(t => t.BaseType == baseType))
.ToArray();
return types;
}
public static Type[] GetAllBackgroundService()
{
return GetAllChildClass(typeof(BackgroundService));
}
MongoClientSettings settings = new MongoClientSettings
{
WaitQueueSize = int.MaxValue,
WaitQueueTimeout = new TimeSpan(0, 2, 0),
MinConnectionPoolSize = 1,
MaxConnectionPoolSize = 100,
ConnectTimeout = TimeSpan.FromSeconds(10),
Server = new MongoServerAddress(_connectionString)
}
https://www.raydbg.com/2018/Debugging-Net-Core-on-Linux-with-LLDB/
To gather detailed information about a performance issue of .NET Core Application on Linux, you can follow the simple instructions here:
curl -OL http://aka.ms/perfcollect
chmod +x perfcollect
sudo ./perfcollect install
export COMPlus_PerfMapEnabled=1
export COMPlus_EnableEventLog=1
./perfcollect collect tracefile
createdump [options] pid -f, --name - dump path and file name. The pid can be placed in the name with %d. The default is "/tmp/coredump.%d" -n, --normal - create minidump (default). -h, --withheap - create minidump with heap. -t, --triage - create triage minidump. -u, --full - create full core dump. -d, --diag - enable diagnostic messages.
Install-Package Caching.CSRedis -Version 3.1.6
services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
Assembly asm = Assembly.GetExecutingAssembly(); asm.GetTypes() .Where(type=> typeof(Controller).IsAssignableFrom(type)) //filter controllers .SelectMany(type => type.GetMethods()) .Where(method => method.IsPublic && ! method.IsDefined(typeof(NonActionAttribute)));
Reference:
services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = "SampleInstance"; });
createdump
http://www.vnfan.com/robin/d/df6441c4dcaa7b82.html
定時任務:
https://blog.csdn.net/phker/article/details/87088394
If you want see your buffer size in terminal, you can take a look at:
/proc/sys/net/ipv4/tcp_rmem
(for read)/proc/sys/net/ipv4/tcp_wmem
(for write)
public Task SetupDatabaseAsync() { var t1 = CreateTableAsync<Session>(); var t2 = CreateTableAsync<Speaker>(); return Task.WhenAll(t1, t2); }
var tasks =
new
List<Task>();
tasks.Add(StartNewTask());
tasks.Add(StartNewTask());
await Task.WhenAll(tasks);
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
int failed = 0;
var tasks = new List<Task>();
String[] urls = { "www.adatum.com", "www.cohovineyard.com",
"www.cohowinery.com", "www.northwindtraders.com",
"www.contoso.com" };
foreach (var value in urls) {
var url = value;
tasks.Add(Task.Run( () => { var png = new Ping();
try {
var reply = png.Send(url);
if (! (reply.Status == IPStatus.Success)) {
Interlocked.Increment(ref failed);
throw new TimeoutException("Unable to reach " + url + ".");
}
}
catch (PingException) {
Interlocked.Increment(ref failed);
throw;
}
}));
}
Task t = Task.WhenAll(tasks.ToArray());
try {
await t;
}
catch {}
if (t.Status == TaskStatus.RanToCompletion)
Console.WriteLine("All ping attempts succeeded.");
else if (t.Status == TaskStatus.Faulted)
Console.WriteLine("{0} ping attempts failed", failed);
}
}
// The example displays output like the following:
// 5 ping attempts failed
private async Task Execute() { string tags = ConfigurationManager.AppSettings["HTMLTags"]; var cursor = Mouse.OverrideCursor; Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; List<Task> tasks = new List<Task>(); foreach (string tag in tags.Split(';')) { tasks.Add(ReadImagesAsync(tag)); //tasks.Add(Task.Run(() => ReadImages(tag))); } await Task.WhenAll(tasks.ToArray()); Mouse.OverrideCursor = cursor; }
若是這是WPF,那麼我肯定你會在某種事件發生時調用它.你應該調用這個方法的方法來自事件處理程序,例如:
private async void OnWindowOpened(object sender, EventArgs args) { await Execute(); }
看看你的問題的編輯版本,我能夠看到,實際上你能夠經過使用異步版本的DownloadStringAsync使它變得很是漂亮和漂亮:
private async Task ReadImages (string HTMLtag) { string section = HTMLtag.Split(':')[0]; string tag = HTMLtag.Split(':')[1]; List<string> UsedAdresses = new List<string>(); var webClient = new WebClient(); string page = await webClient.DownloadStringAsync(Link); //... }
如今,處理任務是什麼.添加(Task.Run(()=> ReadImages(tag)));?
private async Task Execute() { string tags = ConfigurationManager.AppSettings["HTMLTags"]; var cursor = Mouse.OverrideCursor; Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; List<Task> tasks = new List<Task>(); foreach (string tag in tags.Split(';')) { tasks.Add(ReadImagesAsync(tag)); //tasks.Add(Task.Run(() => ReadImages(tag))); } await Task.WhenAll(tasks.ToArray()); Mouse.OverrideCursor = cursor; }
private async void OnWindowOpened(object sender, EventArgs args) { await Execute(); }
private async Task ReadImagesAsync(string HTMLtag) { await Task.Run(() => { ReadImages(HTMLtag); }).ConfigureAwait(false); }
requestTimeout="00:20:00"
mongodb
var conventionPack = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("camelCase", conventionPack, t => true);
https://www.sslforfree.com/
?using System;
using System.Collections.Generic;
using System.Net.Http;
namespace com.baidu.ai
{
public static class AccessToken
{
// 調用getAccessToken()獲取的 access_token建議根據expires_in 時間 設置緩存
// 返回token示例
public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
// 百度雲中開通對應服務應用的 API Key 建議開通應用的時候多選服務
private static String clientId = "百度雲應用的AK";
// 百度雲中開通對應服務應用的 Secret Key
private static String clientSecret = "百度雲應用的SK";
public static String getAccessToken() {
String authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result; String result = response.Content.ReadAsStringAsync().Result; Console.WriteLine(result); return result; } }}