.net core2.2
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));
[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=1export 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");
.net core2.2的更多相关文章
- 一步步学习EF Core(3.EF Core2.0路线图)
前言 这几天一直在研究EF Core的官方文档,暂时没有发现什么比较新的和EF6.x差距比较大的东西. 不过我倒是发现了EF Core的路线图更新了,下面我们就来看看 今天我们来看看最新的EF Cor ...
- .Net Framework下对Dapper二次封装迁移到.Net Core2.0遇到的问题以及对Dapper的封装介绍
今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...
- 一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx、supervisor、mysql环境搭建
作为.neter,看到.net core 2.0的正式发布,心里是有点小激动的,迫不及待的体验了一把,发现速度确实是快了很多,其中也遇到一些小问题,所以整理了一些学习笔记: 阅读目录 环境说明 安装C ...
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...
- Centos7.2下Nginx配置SSL支持https访问(站点是基于.Net Core2.0开发的WebApi)
准备工作 1.基于nginx部署好的站点(本文站点是基于.Net Core2.0开发的WebApi,有兴趣的同学可以跳http://www.cnblogs.com/GreedyL/p/7422796. ...
- .NET Core2.0 MVC中使用EF访问数据
使用环境:Win7+VS2017 一.新建一个.NET Core2.0的MVC项目 二.使用Nuget添加EF的依赖 输入命令:Install-Package Microsoft.EntityFram ...
- 一步一步带你做WebApi迁移ASP.NET Core2.0
随着ASP.NET Core 2.0发布之后,原先运行在Windows IIS中的ASP.NET WebApi站点,就可以跨平台运行在Linux中.我们有必要先说一下ASP.NET Core. ASP ...
- asp.net core2.0网站的环境搭建和网站部署
使用到的软件和硬件 1. centos7.3服务器一台 2. xshell.xftp 3. vs2017 4. .NET Core 1. 安装 li ...
- 前端基于react,后端基于.net core2.0的开发之路(1) 介绍
文章提纲目录 1.前端基于react,后端基于.net core2.0的开发之路(1) 介绍 2.前端基于react,后端基于.net core2.0的开发之路(2) 开发环境的配置,注意事项,后端数 ...
- 前端基于react,后端基于.net core2.0的开发之路(2) 开发环境的配置,注意事项,后端数据初始化
前端环境配置 项目介绍文章:前端基于react,后端基于.net core2.0的开发之路(1) 介绍 1.VSCode安装 下载地址:https://code.visualstudio.com/Do ...
随机推荐
- 如何通过Chrome远程调试android设备上的Web网站
网上的帖子很多,但很多都是老版本的,试过了,根本不管用,花了一天时间,终于在本机试验通过了,特记录下来,以备用.有需要的朋友也可以参考.先上一张图,看看PC端chrome上调试的效果: 左边是手机的模 ...
- JDBC 链接mysql 8 的问题
转载:jdbc连接mysql 8 的一些坑 1.驱动包要升级为 mysql-connector-java-8.0.11.jar 2.JDBC driver 由“com.mysql.jdbc.Drive ...
- redux源码图解:createStore 和 applyMiddleware
在研究 redux-saga时,发现自己对 redux middleware 不是太了解,因此,便决定先深入解读一下 redux 源码.跟大多数人一样,发现 redux源码 真的很精简,目录结构如下: ...
- vue 新建项目
1. 首先安装node.js,安装时一直点Next,知道Finish就可以安装成功 2. 打开控制命令执行程序cmd,输入node -v ,可以查看node的版本信息,即安装成功,我安装的是v8.12 ...
- ionic2简单分析
Angular2是一个全新的框架,它从ReactJS以及其他web移动框架借鉴了不少经验和优点,巨大的改进使得开 发体验和性能已经超越了Angular1,而且Ionic2无论是从UI交互效果和跨平台的 ...
- JVM垃圾收集器-Parallel Scavenge收集器
今天我给大家讲讲JVM垃圾收集器-Parallel Scavenge收集器 Parallel Scavenge收集器 Parallel Scavenge收集器也是一个新生代收集器,它也是使用复制算法的 ...
- 关于crontab
crontab是一个linux系统自带的定时执行任务的功能,有两种方法可以实现 1: 使用命令 crontab -e 然后直接编辑定时脚本,实际是编辑/var/spool/cron 目录下,一个和用户 ...
- RABBITMQ too many heartbeats missed
执行rabbitmqctl status | grep -A 4 file_descriptors 显示socket_used 达到 socket_limited 的值 增加socket_limi ...
- Java技术开发程序员如果在2019年立足
2019年的互联网环境相对以往来说要更复杂一些,互联网领域也正在经历从消费互联网向产业互联网转型的阵痛期.其实不少公司从2018年开始已经在陆续进行结构化调整,这些调整中的重要内容就是岗位调整,而岗位 ...
- .net core 存储base64的图片或文件
public void SaveImageFromBase64(string base64string) { byte[] b = Convert.FromBase64String(base64str ...