zwei1121

博客园 首页 新随笔 联系 订阅 管理
  1. @foreach (var section in Model.Article.Sections)
  2. {
  3. @await Html.PartialAsync("_ArticleSectionRP", section,
  4. new ViewDataDictionary(ViewData)
  5. {
  6. { "index", index }
  7. })
  8. index++;
  9. }
  1. <partial name="_ProductViewDataPartial" for="Product" view-data="ViewData">

 

services.AddRouting(options => options.LowercaseUrls = true);

 

/aa/bb/cc

Regex.Replace("", @"(\w{2}(?=[^$]))", "$1/");

 

 

<PackageReference Include="" Version="3.4.1" >
<IncludeAssets>all</IncludeAssets>
<ExcludeAssets>contentFiles</ExcludeAssets>
<PrivateAssets>contentFiles;analyzers</PrivateAssets>
</PackageReference>

 

https://andrewlock.net/model-binding-json-posts-in-asp-net-core/

 https://blog.csdn.net/shujudeliu/article/details/86293167

 

Unit Test Boilerplate Generator:一键将要测试的方法生成单元测试。

Unit Test Generator:一键将要测试的方法生成单元测试。

 

private static readonly ILogger _logger = ApplicationLogger.CreateLogger("RoleService");

 

IdentityModelEventSource.ShowPII = true;

 

services.AddSwaggerGen(c =>
{
  c.SwaggerDoc("v1", new OpenApiInfo { 
    Title = "My API", 
    Version = "v1" 
  });
  c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
    In = ParameterLocation.Header, 
    Description = "Please insert JWT with Bearer into field",
    Name = "Authorization",
    Type = SecuritySchemeType.ApiKey 
  });
  c.AddSecurityRequirement(new OpenApiSecurityRequirement {
   { 
     new OpenApiSecurityScheme 
     { 
       Reference = new OpenApiReference 
       { 
         Type = ReferenceType.SecurityScheme,
         Id = "Bearer" 
       } 
      },
      new string[] { } 
    } 
  });
});

using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
//string data = Encoding.UTF8.GetString(inputByts);//转为String
//data = data.Replace("{\"encrypt\":\"", "").Replace("\"}", "");
//return data;
}

DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);
DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance);

 

private IDistributedCache _cache;
public IDistributedCache Cache
{
get
{
if (_cache == null)
{
_cache = (IDistributedCache)HttpContext.RequestServices.GetService(typeof(IDistributedCache));
}
return _cache;
}
set
{
_cache = value;
}
}

var actionDescriptor = context.ActionDescriptor;
var isAllowAnonymous = actionDescriptor.EndpointMetadata.Any(p=>p is AllowAnonymousAttribute);

 

public static bool IsUnix { get; } = Environment.CurrentDirectory[0] == '/';

 

typeFaqs.ForEach(async p=>{
var result=await
});


<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
打开工程文件

 

Task.Factory.StartNew(s =>
{
var context=(HttpContext)s;
//传context至方法中
},HttpContext.Current);

 

 

dotnet sql-cache create "Data Source=.;Initial Catalog=test;Integrated Security=True;" dbo TestCache

CREATE TABLE [dbo].[TestCache](
[Id] [nvarchar](449) NOT NULL,
[Value] [varbinary](max) NOT NULL,
[ExpiresAtTime] [datetimeoffset](7) NOT NULL,
[SlidingExpirationInSeconds] [bigint] NULL,
[AbsoluteExpiration] [datetimeoffset](7) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]



https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2?view=netframework-4.7.2
private readonly IDataProtector _dataProtector; public DiscussionController(IDataProtectionProvider dataProtectionProvider) { _dataProtector = dataProtectionProvider.CreateProtector(nameof(SessionMiddleware)); } public ViewResult Index() {

var bb = Request.Cookies[".AspNetCore.Session"];
var aa = HttpContext.Session.Id;


   string cookieValue;
   HttpContext.Request.Cookies.TryGetValue(".AspNetCore.Session", out cookieValue);

   var protectedData = Convert.FromBase64String(Pad(cookieValue));

   var unprotectedData = _dataProtector.Unprotect(protectedData);

   string humanReadableData = System.Text.Encoding.UTF8.GetString(unprotectedData);
 return Content(bb + "\r\n" + aa + "\r\n" + humanReadableData);
}

The pad function is from https://github.com/aspnet/Session/blob/dev/src/Microsoft.AspNetCore.Session/CookieProtection.cs

https://stackoverflow.com/questions/43326061/net-core-machine-key-alternative-for-webfarm

 

[Reference(ReferenceType.Many, ColumnName = "OneId", ReferenceMemberName = "OneId")]

var user = Database.FetchOneToMany<UserDecoratedWithExtraInfoAsList>(
x => x.ExtraUserInfo,
x => x.UserId,
"select u.*, e.* from users u left join extrauserinfos e on u.userid = e.userId where u.userid = 1").Single();

 

 

class MyURLSearchParams extends URLSearchParams {
  toString(): string {
    const params = {};
    this.paramsMap.forEach((v, k) => {
      params[k] = v[0];
    });
    return $.param(params); // or any other your custom function you use to serialize search query
  }
}

const params = new URLSearchParams() params.append('date', '2018') params.append('date', '8') params.append('date', '13') console.log(params.toString()) // date=2018&date=8&date=13 params.set('date', '20180813') console.log(params.toString()) // date=20180813
const searchParams = new URLSearchParams();

You can keep one server as primary and one as secondary. In the secondary server disable auto key generation

public void ConfigureServices(IServiceCollection services)
{
     services.AddDataProtection().DisableAutomaticKeyGeneration();
}

Or you can persist them to Redis

public void ConfigureServices(IServiceCollection services)
{
    // sad but a giant hack :(
    // https://github.com/StackExchange/StackExchange.Redis/issues/410#issuecomment-220829614
    var redisHost = Configuration.GetValue<string>("Redis:Host");
    var redisPort = Configuration.GetValue<int>("Redis:Port");
    var redisIpAddress = Dns.GetHostEntryAsync(redisHost).Result.AddressList.Last();
    var redis = ConnectionMultiplexer.Connect($"{redisIpAddress}:{redisPort}");

    services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");
    services.AddOptions();

    // ...
}




[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme + ", " + Microsoft.AspNetCore.Identity.IdentityConstants.ApplicationScheme)]
 


var task = Task.Factory.StartNew( state => { var context = (HttpContext) state; //use context }, HttpContext.Current);
 
Task.Factory.StartNew(s =>
{
var context=(HttpContext)s;
//传context
},HttpContext.Current);
 
 
private readonly IDistributedCache _distributedCache;
  
    public HomeController(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }

 

services.AddMvc()
.AddMvcOptions(options =>
{
options.Filters.Add(new SampleActionFilter());
options.Filters.Add(new SampleAsyncActionFilter());
});

0.0.0.1

ServiceFilterAttribute
TypeFilterAttribute
IFilterFactory

 

dotNet Core 内存占用过高的解决方案 

https://blog.csdn.net/qq_36051316/article/details/83054446

 

发布:https://blog.csdn.net/qq4165498/article/details/77484530

@await Html.PartialAsync("_LoginPartial")

@Request.Url.AbsoluteUri
@Context.Request.Host@Context.Request.Path

HttpContext.Current doesn't exist anymore in ASP.NET Core but there's a newIHttpContextAccessor that you can inject in your dependencies and use to retrieve the current HttpContext:

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public string GetDataFromSession()
    {
        return _contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}


ConfigurationBuilder

https://stackoverflow.com/questions/37597300/net-core-dapper-connection-string

https://stackoverflow.com/questions/39083372/how-to-read-connection-string-in-net-core

 https://blog.csdn.net/sD7O95O/article/details/78096117

 

 

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

If you need it from a Controller, then just use HttpContext, as Muqeet's answer says.

If you do need to inject it, then you're on the right track with AddSingleton, but you have a slight typo:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Notice the I in the first type.

Then set up your constructor:

public class UserService : IUserService {
    private readonly HttpContext _context;

    public UserService(IHttpContextAccessor httpContextAccessor) {
        _context = httpContextAccessor.HttpContext;
    }
}
 

services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

 

https://cloud.tencent.com/developer/ask/141577


services.AddMvc()  
       .AddJsonOptions(options =>  
       {  
         options.SerializerSettings.DateTimeZoneHandling = "MM/dd/yyyy HH:mm:ss";  
       });  
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"
services.AddMvc().AddJsonOptions(options =>
                {
                    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                });
 

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;

builder.AddJsonFile("appsettings.json",
optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);

if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(
new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
builder.AddUserSecrets(appAssembly, optional: true);
}
}

builder.AddEnvironmentVariables();

if (args != null)
{
builder.AddCommandLine(args);
}
})
.Build();

 

 

https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/

https://stackoverflow.com/questions/32558941/render-razor-view-to-string-in-asp-net-core

https://stackoverflow.com/questions/38247080/using-razor-outside-of-mvc-in-net-core

https://stackoverflow.com/questions/39776009/render-a-razor-view-containing-a-url-to-a-string-in-asp-net-core

https://www.codemag.com/article/1312081/Rendering-ASP.NET-MVC-Razor-Views-to-String

https://stackoverflow.com/questions/483091/how-to-render-an-asp-net-mvc-view-as-a-string

 

class FakeController : ControllerBase
{
    protected override void ExecuteCore() { }
    public static string RenderViewToString(string controllerName, string viewName, object viewData)
    {
        using (var writer = new StringWriter())
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController());
            var razorViewEngine = new RazorViewEngine();
            var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
            razorViewResult.View.Render(viewContext, writer);
            return writer.ToString();

        }
    }
}
public class HomeController : ApiController
 {
   [HttpGet]
   [Route("/")]
   public HttpResponseMessage Get()
   {
     var content = new StreamContent(this.GetType().Assembly.GetManifestResourceStream(this.GetType(),"home.html"));
     content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
     return new HttpResponseMessage() { Content = content };
   }
 }

 

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");



HttpRequestMessage contains constructor taking instance of HttpMethod but there is no ready constructor that converts HTTP method string to HttpMethod, so you can't avoid that switch (in one form or another).

However you should not have duplicated code under different switch cases, so implementation would be something like this:

private HttpMethod CreateHttpMethod(string method)
{
    switch (method.ToUpper())
    {
        case "POST":
            return HttpMethod.Post;
        case "GET":
            return HttpMethod.Get;
        default:
            throw new NotImplementedException();
    }
}

public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
{
    var request = new HttpRequestMessage(CreateHttpMethod(method), url)
    {
        Content = content
    };

    return await client.SendAsync(request);
}

protected virtual Task LoadDataAsync() {
  return Task.FromResult(default(object));
}

在 IIS 中托管应用并添加或更改 ASPNETCORE_ENVIRONMENT 环境变量时,请采用下列方法之一,让新值可供应用拾取:

  • 在命令提示符处依次执行 net stop was /y 和 net start w3svc
  • 重启服务器。

 

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments?view=aspnetcore-2.1

        string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

 #!/usr/bin/python

 


using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

namespace Web.Middlewares
{
    public class OptionsMiddleware
    {
        private readonly RequestDelegate _next;
        private IHostingEnvironment _environment;

        public OptionsMiddleware(RequestDelegate next, IHostingEnvironment environment)
        {
            _next = next;
            _environment = environment;
        }

        public async Task Invoke(HttpContext context)
        {
            this.BeginInvoke(context);
            await this._next.Invoke(context);
        }

        private async void BeginInvoke(HttpContext context)
        {
            if (context.Request.Method == "OPTIONS")
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
                context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
                context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
                context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync("OK");
            }
        }
    }

    public static class OptionsMiddlewareExtensions
    {
        public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<OptionsMiddleware>();
        }
    }
}

Then add app.UseOptions(); this as the first line in Startup.cs in the Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseOptions();
}



Create a MapperConfiguration instance and initialize configuration via the constructor:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Foo, Bar>();
    cfg.AddProfile<FooProfile>();
});

The MapperConfiguration instance can be stored statically, in a static field or in a dependency injection container. Once created it cannot be changed/modified.

Alternatively, you can use the static Mapper instance to initialize AutoMapper:

Mapper.Initialize(cfg => {
    cfg.CreateMap<Foo, Bar>();
    cfg.AddProfile<FooProfile>();
});



#region 配置cookie策略
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                //options.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always;
                options.MinimumSameSitePolicy = SameSiteMode.Strict;
            });
            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
#endregion
#region 配置分布式缓存及session
            //core自带库
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = Configuration.GetConnectionString("RedisDB.Session");
                options.InstanceName = "";
            });
            //第三方库
            //services.AddSingleton<IDistributedCache>(new CSRedisCache(new CSRedis.CSRedisClient(Configuration.GetConnectionString("RedisDB.Session"))));
            services.AddSession(options =>
            {
                options.Cookie.Name = "fxi.web";
                options.Cookie.HttpOnly = true;
                options.Cookie.SameSite = SameSiteMode.Strict;
                //options.Cookie.SecurePolicy = CookieSecurePolicy.Always;  //https 才附带cookie
                options.Cookie.IsEssential = true;
            });
#endregion
#region 配置数据保护
            var redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("RedisDB.Web"));
            services.AddDataProtection(option => option.ApplicationDiscriminator = "fxi.tdpx")
                .DisableAutomaticKeyGeneration()
                .SetApplicationName("fxi.tdpx")
                .PersistKeysToStackExchangeRedis(redis)
                .ProtectKeysWithCertificate(new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "client.fxi"));
#endregion
 
 

public static string FormatTags(string oldTags, string newTags)
{
var result = "";
if (string.IsNullOrEmpty(oldTags) && string.IsNullOrEmpty(newTags))
{
return string.Empty;
}
var tags = oldTags + "," + newTags;
var tagList = tags.TrimEnd(',').Split(',').ToList();
if (tagList != null && tagList.Count > 0)
{
tagList.RemoveAll(p => string.IsNullOrEmpty(p));
result = string.Join(',', tagList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct());
}
return result;
}

 

public static IConfiguration GetConfig()
{
var envVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
var env = $"env: {envVariable}";
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{envVariable}.json", optional: true)
.Build();

ConfigHelper.SetConfig(config);
return config;
}

 

public static AppSettings GetSettings()
{
var config = GetConfig();
//var services = new ServiceCollection();
//var serviceProvider = services.BuildServiceProvider();
//services.ConfigureDbContext(config);

var path = Assembly.GetExecutingAssembly().Location.Replace("ThesisForm.MSUnitTest.dll", "");
LogManager.Configuration = new XmlLoggingConfiguration(path + "NLog.config");
//装载数据类型转换
AutoMappingProfile.Configure();
var result = config.Get<AppSettings>();
return result;


}

 

 

  1. providerInvariantNames.Add(DbProviderType.SqlServer, "System.Data.SqlClient"); 
  2.             providerInvariantNames.Add(DbProviderType.OleDb, "System.Data.OleDb"); 
  3.             providerInvariantNames.Add(DbProviderType.ODBC, "System.Data.ODBC"); 
  4.             providerInvariantNames.Add(DbProviderType.Oracle, "Oracle.DataAccess.Client"); 
  5.             providerInvariantNames.Add(DbProviderType.MySql, "MySql.Data.MySqlClient"); 
  6.             providerInvariantNames.Add(DbProviderType.SQLite, "System.Data.SQLite"); 
  7.             providerInvariantNames.Add(DbProviderType.Firebird, "FirebirdSql.Data.Firebird"); 
  8.             providerInvariantNames.Add(DbProviderType.PostgreSql, "Npgsql"); 
  9.             providerInvariantNames.Add(DbProviderType.DB2, "IBM.Data.DB2.iSeries"); 
  10.             providerInvariantNames.Add(DbProviderType.Informix, "IBM.Data.Informix"); 
  11.             providerInvariantNames.Add(DbProviderType.SqlServerCe, "System.Data.SqlServerCe"); 
posted on 2018-05-18 14:48  zwei  阅读(307)  评论(0)    收藏  举报