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).
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 line
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
集合
Linq
压缩
加密
数学运算
序列化
文字处理
文件系统
网络
并发
[TypeFilter(typeof())]
[ServiceFilter(typeof())]
https://docs.microsoft.com/en-us/aspnet/core/migration/21-to-22?view=aspnetcore-2.2&tabs=visual-studio#call-configurekestrel-instead-of-usekestrel
https://devblogs.microsoft.com/aspnet/asp-net-core-2-2-0-preview2-now-available/
https://www.cnblogs.com/stulzq/p/10069412.html
var path = Directory.GetCurrentDirectory();
dotnet tool install --global dotnet-dump --version 3.0.47001
https://garywoodfine.com/ihost-net-core-console-applications/
<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>
<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 发布用于独立部署:
<?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>
<PropertyGroup> <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> </PropertyGroup>
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
- public class ConsumeRabbitMQHostedService : BackgroundService
- {
- private readonly ILogger _logger;
- private IConnection _connection;
- private IModel _channel;
- public ConsumeRabbitMQHostedService(ILoggerFactory loggerFactory)
- {
- this._logger = loggerFactory.CreateLogger<ConsumeRabbitMQHostedService>();
- InitRabbitMQ();
- }
- private void InitRabbitMQ()
- {
- var factory = new ConnectionFactory { HostName = "localhost" };
- // create connection
- _connection = factory.CreateConnection();
- // create channel
- _channel = _connection.CreateModel();
- _channel.ExchangeDeclare("demo.exchange", ExchangeType.Topic);
- _channel.QueueDeclare("demo.queue.log", false, false, false, null);
- _channel.QueueBind("demo.queue.log", "demo.exchange", "demo.queue.*", null);
- _channel.BasicQos(0, 1, false);
- _connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;
- }
- protected override Task ExecuteAsync(CancellationToken stoppingToken)
- {
- stoppingToken.ThrowIfCancellationRequested();
- var consumer = new EventingBasicConsumer(_channel);
- consumer.Received += (ch, ea) =>
- {
- // received message
- var content = System.Text.Encoding.UTF8.GetString(ea.Body);
- // handle the received message
- HandleMessage(content);
- _channel.BasicAck(ea.DeliveryTag, false);
- };
- consumer.Shutdown += OnConsumerShutdown;
- consumer.Registered += OnConsumerRegistered;
- consumer.Unregistered += OnConsumerUnregistered;
- consumer.ConsumerCancelled += OnConsumerConsumerCancelled;
- _channel.BasicConsume("demo.queue.log", false, consumer);
- return Task.CompletedTask;
- }
- private void HandleMessage(string content)
- {
- // we just print this message
- _logger.LogInformation($"consumer received {content}");
- }
- private void OnConsumerConsumerCancelled(object sender, ConsumerEventArgs e) { }
- private void OnConsumerUnregistered(object sender, ConsumerEventArgs e) { }
- private void OnConsumerRegistered(object sender, ConsumerEventArgs e) { }
- private void OnConsumerShutdown(object sender, ShutdownEventArgs e) { }
- private void RabbitMQ_ConnectionShutdown(object sender, ShutdownEventArgs e) { }
- public override void Dispose()
- {
- _channel.Close();
- _connection.Close();
- base.Dispose();
- }
- }
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)
}
PerfView
https://www.raydbg.com/2018/Debugging-Net-Core-on-Linux-with-LLDB/
Profiling the .NET Core Application on Linux
To gather detailed information about a performance issue of .NET Core Application on Linux, you can follow the simple instructions here:
- Download perfcollect script provided by .NET Core team.
curl -OL http://aka.ms/perfcollect
- Make the script executable.
chmod +x perfcollect
- Install prerequisites (perf and LTTng):
sudo ./perfcollect install
- Setup the application shell and enables tracing configuration:
export COMPlus_PerfMapEnabled=1
export COMPlus_EnableEventLog=1
- Run collection:
./perfcollect collect tracefile
- Copy the tracefile.zip file to a Windows machine.
- Download PerfView on Windows box.
- Open the trace in PerfView, then you can explore the CPU sampling data. Flame Graph is also available here.
Using BPF Complier Collection (BCC) is another good choice for performance analysis as BPF is more flexible and efficiency. Please follow the tutorial of BCC.
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;
}
}
}
It looks like your numbers are in a single string separated by spaces if so you can use Linq:
List<int> allNumbers = numbers.Split(' ').Select(int.Parse).ToList();
If you really have a List<string>
numbers already simply:
List<int> allNumbers = numbers.Select(int.Parse).ToList();
Or finally, if each string may contain multiple numbers separated by spaces:
List<int> allNumbers = numbers.SelectMany(x=> x.Split(' ')).Select(int.Parse).ToList();
Process.Start("CMD.exe", "/K yarn run start");
Process.Start("cmd", "/C start http://localhost:3000");
you can use
Task.Delay(2000).Wait(); // Wait 2 seconds with blocking
await Task.Delay(2000); // Wait 2 seconds without blocking
[ApiExplorerSettings(IgnoreApi = true)]
[HttpPost("test")]
[Consumes("text/plain", new[] { "text/html" })]
Thread.Sleep((new Random().Next(1,6))*1000);
[assembly: AspMvcViewLocationFormat(@"~/../ClassLibrary")]
In asp.net core 3.0 with endpoint routing enabled, you could register IHttpContextAccessor
to get the current HttpContext, then you could get the http
method.
Take below Policy-based authorization as an example:
public class AccountRequirement : IAuthorizationRequirement { }
public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AccountHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{
var httpMethod = _httpContextAccessor.HttpContext.Request.Method;
if (httpMethod == "POST")
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
In Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
options.AddPolicy("Account",
policy => policy.Requirements.Add(new AccountRequirement()));
});
services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}
var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = errorFeature.Error;
public string showURL(IHttpContextAccessor httpcontextaccessor)
{
var request = httpcontextaccessor.HttpContext.Request;
var absoluteUri = string.Concat(
request.Scheme,
"://",
request.Host.ToUriComponent(),
request.PathBase.ToUriComponent(),
request.Path.ToUriComponent(),
request.QueryString.ToUriComponent());
return absoluteUri;
}
private readonly IMapper _mapper;
private readonly MapperConfiguration _mapperConfig;
private readonly DataContext _dataContext;
public ValuesController(IMapper mapper, DataContext dataContext, MapperConfiguration mapperConfig)
{
_mapper = mapper;
_dataContext = dataContext;
_mapperConfig = mapperConfig;
}
services.AddScoped<IBaseContext, BaseCoreContext>();
//泛型引用方式
services.AddScoped(typeof(IBaseServices<>), typeof(BaseServices<>));
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
services.RegisterAssembly("IServices");
services.RegisterAssembly("IRepository");