我在向.NET Core类库中的Entity Framework数据库上下文添加初始迁移时遇到问题.
当我跑:
dotnet ef migrations add migrationName -c PlaceholderContext
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Could not invoke this command on the startup project 'Placeholder.Data'. This version of the Entity Framework Core .NET Command Line Tools does not support commands on class library projects in ASP.NET Core and .NET Core applications. See http://go.microsoft.com/fwlink/?LinkId=798221 for details and workarounds.
Run Code Online (Sandbox Code Playgroud)
所以我点击了链接,了解到无法将迁移添加到类库中.但是,您可以将类库项目转换为"app"项目,但通过这样做,我无法从业务层(类库)引用此"app"项目.
项目结构:
Placeholder.Web(WebAPI)=> Placeholder.Business(类库)=> Placeholder.Data(类库)
Placeholder.Web => Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
//HERE WE …Run Code Online (Sandbox Code Playgroud) 我正在使用Unity.MVC4依赖注入来访问我的服务.注入到我的Controller构造函数中时,一切都正常,但我现在要做的是在我的过滤器类中使用属性注入,这样我就可以从内部访问我的数据库了.
在我开始这个问题之前,我用Google搜索并尝试了不同的示例,但我找不到适合我的解决方案..
Bootstrapper.cs
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IAccountRepository, AccountRepository>();
container.RegisterType<IAdministrationRepository, AdministrationRepository>();
container.RegisterType<IUploadDirectlyRepository, UploadDirectlyRepository>();
container.RegisterType<IUserRepository, UserRepository>();
container.RegisterType<INewsRepository, NewsRepository>();
container.RegisterType<IContactRepository, ContactRepository>();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{ …Run Code Online (Sandbox Code Playgroud) asp.net-mvc dependency-injection unity-container action-filter asp.net-mvc-4
我使用自己的JWT令牌身份验证,而不使用默认模板附带的asp.net身份。我到处都到处寻找有关如何在没有asp.net身份的情况下实现外部身份验证的文档/指南,但是所有文章都涉及asp.net身份验证。
我已经设法将用户重定向到google登录页面(使用ChallengeResult),但是当提供程序重定向回该应用程序时,我失败了。
我删除了:app.UseAuthentication(); 在Startup.cs中,(禁用身份验证),然后可以使用回调函数,但是我不知道如何在不使用登录管理器的情况下从响应中检索数据。
启动
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Authentication:Secret"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = Configuration["Urls:Base"],
ValidateAudience = true,
ValidAudience = Configuration["Urls:Base"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o …Run Code Online (Sandbox Code Playgroud) 我一直在使用NUnit进行测试,我真的很喜欢测试用例.在NUnit中,您可以使用TestCaseData类中的SetName函数轻松地在测试用例中设置每个测试名称.
xUnit是否具有类似的功能?
目前我只能在测试资源管理器中看到一个测试,即使我在测试用例中有6个测试.
xUnit测试
public class LogHandler : TestBase
{
private ILogger _logger;
public LogHandler()
{
//Arrange
LogAppSettings logAppSettings = GetAppSettings<LogAppSettings>("Log");
IOptions<LogAppSettings> options = Options.Create(logAppSettings);
LogService logService = new LogService(new Mock<IIdentityService>().Object, options);
LogProvider logProvider = new LogProvider(logService);
_logger = logProvider.CreateLogger(null);
}
public static IEnumerable<object[]> TestCases => new[]
{
new object[] { LogLevel.Critical,
new EventId(),
new Exception(),
1 },
new object[] { LogLevel.Error,
new EventId(),
new Exception(),
1 },
new object[] { LogLevel.Warning,
new EventId(),
new Exception(),
0 },
new object[] …Run Code Online (Sandbox Code Playgroud) 我希望用户能够从我的网站下载blob.我想要最快/ cheapeast /最好的方式来做到这一点.
这是我想出的:
CloudBlobContainer blobContainer = CloudStorageServices.GetCloudBlobsContainer();
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
Response.ContentType = blob.Properties.ContentType;
Response.AddHeader("Content-Disposition", "Attachment; filename=" + fileName + fileExtension);
Response.AddHeader("Content-Length", (blob.Properties.Length).ToString());
Response.BinaryWrite(memStream.ToArray());
Response.End();
Run Code Online (Sandbox Code Playgroud)
我现在正在使用内存流,但是我猜我应该使用文件流,因为在某些情况下,blob是大的..对吧?
我尝试使用文件流,但我失败了.想想你可以给我一些文件流的代码吗?
我希望我的bootstrap dropdown meny位于鼠标位置.由于某种原因,pageX和pageY是错误的.为了纠正我必须在x和y中加或减的位置.但是,如果我然后放大或缩小,则X和Y再次不正确.我已经尝试了一切.这是其中之一..
HTML:
<div class="dropdown">
<div id="menuitems" onclick="setposition(event)" class="dropdown-toggle" data-toggle="dropdown">
Menu
</div>
<ul class="dropdown-menu" id="xxx" role="menu" aria-labelledby="menuitems">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#"</i>Link 1</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#"</i>Link 2</a></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
脚本
function setposition(e) {
var bodyOffsets = document.body.getBoundingClientRect();
tempX = e.pageX - bodyOffsets.left;
tempY = e.pageY;
$("#xxx").css({ 'top': tempY, 'left': tempX });
}
Run Code Online (Sandbox Code Playgroud)
为了获得不同分辨率的正确X和Y位置,我需要做什么?
谢谢
按照有关如何使用 .NET Core 实现全球化和本地化的文档,我的目标是将所有资源存储在位于不同项目(类库)中的单个全局资源文件中。
项目 1 - Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddLocalization(lo => lo.ResourcesPath = "/MYCLASSLIBRARY"); //External project ~ How?
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.Configure<RequestLocalizationOptions>(
opts => …Run Code Online (Sandbox Code Playgroud) 有预测(0 变化):
var changesBefore = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //before change - 0
var orderLocation = Db.OrderLocation.AsTracking().Select(ol => new OrderLocationEntity
{
Id = ol.Id,
Address = ol.Address,
City = ol.City,
Created = ol.Created,
OrderId = ol.OrderId,
Zip = ol.Zip
}).First();
orderLocation.Address = "address";
var changesAfter = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //after change - 0
Run Code Online (Sandbox Code Playgroud)
没有预测(1 处更改)
var changesBefore = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //before change - 0
var orderLocation = Db.OrderLocation.AsTracking().First();
orderLocation.Address = "address";
var changesAfter = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //after change - 1
Run Code Online (Sandbox Code Playgroud)
设置
微软.EntityFrameworkCore 3.1.1
Microsoft.EntityFrameworkCore.Sqlite 3.1.1
var options …Run Code Online (Sandbox Code Playgroud) c# entity-framework-core .net-core entity-framework-core-3.1
当作为参数传递给 ilogger 时,对象在 Application Insights 自定义维度中呈现为字符串(对象的名称)。未显示实际值。
注册应用洞察
services.AddApplicationInsightsTelemetry();
Run Code Online (Sandbox Code Playgroud)
新日志
public class HealthController : ControllerBase
{
private readonly ILogger<HealthController> _logger;
public HealthController(ILogger<HealthController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
var health = new HealthViewModel()
{
ok = false
};
_logger.LogInformation("Hlep me pls {health}", health);
return Ok(health);
}
}
Run Code Online (Sandbox Code Playgroud)
结果
我不想对每个日志都这样做:
var health = new HealthViewModel()
{
ok = false
};
_logger.LogInformation("Hlep me pls {health}", JsonConvert.SerializeObject(health));
Run Code Online (Sandbox Code Playgroud)
我尝试为应用程序洞察创建一个中间件,但值仍然是对象的名称。
编辑
这好像是
var health = new
{
ok = …Run Code Online (Sandbox Code Playgroud) 我一直在为一些 web api 集成测试模拟 IHttpContextAccessor。我的目标是能够模拟 IHttpContextAccessor 并返回 NameIdentifier 声明和 RemoteIpAddress。
测试
public class InsertUser : TestBase
{
private UserController _userController;
[OneTimeSetUp]
public void OneTimeSetUp()
{
IStringLocalizer<UserController> localizer = A.Fake<IStringLocalizer<UserController>>();
_userController = new UserController(localizer, Mapper, UserService, StatusService, IdentityService);
_userController.ControllerContext = A.Fake<ControllerContext>();
_userController.ControllerContext.HttpContext = A.Fake<DefaultHttpContext>();
var fakeClaim = A.Fake<Claim>(x => x.WithArgumentsForConstructor(() => new Claim(ClaimTypes.NameIdentifier, "1")));
var fakeIdentity = A.Fake<ClaimsPrincipal>();
A.CallTo(() => fakeIdentity.FindFirst(ClaimTypes.NameIdentifier)).Returns(fakeClaim);
A.CallTo(() => _userController.ControllerContext.HttpContext.User).Returns(fakeIdentity);
StatusTypeEntity statusType = ObjectMother.InsertStatusType(StatusTypeEnum.StatusType.User);
StatusEntity status = ObjectMother.InsertStatus(StatusEnum.Status.Active, statusType);
ObjectMother.InsertUser("FirstName", "LastName", "Email@Email.Email", "PasswordHash", "PasswordSalt", status);
}
public …Run Code Online (Sandbox Code Playgroud) c# ×7
.net ×5
asp.net-core ×5
.net-core ×4
asp.net-mvc ×3
azure ×2
asp.net ×1
fakeiteasy ×1
ilogger ×1
javascript ×1
localization ×1
oauth-2.0 ×1
xunit ×1