小编Mat*_*ynn的帖子

全球可访问的Log4Net变量

我目前在application_start中进行了以下设置

log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
Run Code Online (Sandbox Code Playgroud)

现在为了然后注销到log4net我需要向每个控制器添加一个实例;

public static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Run Code Online (Sandbox Code Playgroud)

因为这是我想在整个api中使用的东西.我可以在global.asax中声明这个,这样我就可以调用;

logger.Error( "输出");

什么时候需要?

c# log4net log4net-configuration

6
推荐指数
0
解决办法
683
查看次数

ASP.NET Core中类型Func <T>的依赖项注入

我正在尝试使用asp.net core 2.0.1 for DataContext将Func注入webapi控制器中。

在我的Startup.cs中,我添加了;

services.AddTransient<Func<IDataContext>, Func<DataContext>>();
Run Code Online (Sandbox Code Playgroud)

然后,我在控制器构造函数中将此传递给我的服务;

private readonly ClientService _service;

public ClientController(Func<IDataContext> context)
{
     _service = new ClientService(context);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行该程序并尝试调用端点时,出现了错误;

InvalidOperationException:尝试激活“ System.Func`1 [Data.EF.DataContext]”时,无法解析类型为“ System.Object”的服务。

为什么这是为什么?以及如何解决。

c# dependency-injection asp.net-core-webapi asp.net-core-2.0

6
推荐指数
1
解决办法
2165
查看次数

Blazor 添加 HttpClientHandler 以在请求时将 Jwt 添加到 HTTP 标头

我将Visual Studio 2019.Net Core 3.0.0-preview-7与标准 Blazor 客户端、服务器和共享模板一起使用。

在应用程序中,我们的服务器端 WebApi 应用程序将始终需要一个 JWT 令牌出现在标头中以进行授权。

从以下来看

在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求

我创建了以下处理程序;

public class JwtTokenHeaderHandler : DelegatingHandler
{
    private readonly ILocalStorageService _localStorage;

    public JwtTokenHeaderHandler(ILocalStorageService localStorage)
    {
        _localStorage = localStorage;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (!request.Headers.Contains("bearer"))
        {
            var savedToken = await _localStorage.GetItemAsync<string>("authToken");

            if (!string.IsNullOrWhiteSpace(savedToken))
            {
                request.Headers.Add("bearer", savedToken);
            }
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

我用来Blazored.LocalStorage从 localstorage 获取保存的令牌并将其添加到标题的地方。 …

c# asp.net-core blazor blazor-client-side

5
推荐指数
2
解决办法
9097
查看次数

使用 Blazor 客户端应用程序实现事件订阅

我们的 Blazor 应用程序正在运行preview9

我正在尝试实现一个.razor组件,该组件侦听来自我们编写的 NotificationService 的事件,以便在调用服务时刷新视图,但我似乎遗漏了一些东西;

我有我的服务接口(为简洁起见减少了);

public interface INotificationService
{
    event Action OnChange;
    Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification);
}
Run Code Online (Sandbox Code Playgroud)

在我的实现中,我调用了该OnChange事件(为简洁起见,再次减少);

public async Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification)
{
    /*...*/

    StateChanged();
}
Run Code Online (Sandbox Code Playgroud)

在哪里StateChanged()

public event Action OnChange;

private void StateChanged() => OnChange?.Invoke();
Run Code Online (Sandbox Code Playgroud)

在我的Blazor.Client我决心INotificationServiceConfigureServices如下;

services.AddScoped<INotificationService, NotificationService>();
Run Code Online (Sandbox Code Playgroud)

然后我将服务注入到我想要订阅OnChange()事件的组件中;

 @inject INotificationService NotificationService

 protected override async Task OnInitializedAsync()
 {
     NotificationService.OnChange += StateHasChanged;
 }
Run Code Online (Sandbox Code Playgroud)

然后在我的另一个razor页面中,我再次注入相同的服务并调用该AddNotificationAsync方法;

@inject INotificationService NotificationService

  await …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core blazor blazor-client-side

5
推荐指数
1
解决办法
2267
查看次数

Image.Save 参数无效

我想用另一个图像为文件夹中的文件添加水印。但是,我收到错误

'参数无效'

调用代码时

img.Save(filepath, System.Drawing.Imaging.ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)

我有以下代码;

    public static string WatermarkImagesInFolder(string url)
    {
        if (url == null)
            throw new Exception("URL must be provided");

        string path = HttpContext.Current.Server.MapPath(url);

        if (!Directory.Exists(path))
            throw new DirectoryNotFoundException();

        Directory.CreateDirectory(String.Format(@"{0}\watermarked", path));

        List<string> urls = GetJpgFilesFromFolder(path);

        foreach (string imageUrl in urls)
        {
            Image img = WatermarkImage(imageUrl);

            string filename = Path.GetFileName(imageUrl);
            string filepath = String.Format(@"{0}\watermarked\{1}", path, filename);
            img.Save(filepath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        return "complete";
    }
Run Code Online (Sandbox Code Playgroud)

    public static Image WatermarkImage(string filename)
    {
        using (Image image = Image.FromFile(filename))
        using (Image watermarkImage = Image.FromFile(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WatermarkImageUrl"]))) …
Run Code Online (Sandbox Code Playgroud)

c# asp.net system.io.file

4
推荐指数
1
解决办法
5908
查看次数

EntityTypeBuilder&lt;T&gt; ASP.NET Core 2 实体框架中的 OnDelete

我使用以下模型构建器在我的数据库上设置我的关系。

在我的数据上下文中,我有;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema(schema: DbGlobals.SchemaName);

    modelBuilder.AddConfiguration<Address>(new AddressConfiguration());
    /*reduced for brevity*/

    base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)

其中AddressConfiguration()我有以下内容;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Data.EF.Configuration
{
    internal class AddressConfiguration : DbEntityConfiguration<Address>
    {
        public override void Configure(EntityTypeBuilder<Address> entity)
        {
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Latitude).HasColumnType($"decimal(9,6)").IsRequired();
            entity.Property(x => x.Longitude).HasColumnType($"decimal(9,6)").IsRequired();
            //I have tried the following but it says doesnt exist
            //entity.OnDelete(DeleteBehavior.Cascade);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的地址模型有一个List<Contact> Contacts { get; set; }. 如何配置模型。当地址被删除时删除级联?

我找到了以下链接;

在 EF Core 中删除级联

哪个详细说明了一种OnDelete方法,但是这似乎不存在于EntityTypeBuilder<T> …

c# entity-framework-core asp.net-core-2.0

4
推荐指数
1
解决办法
3648
查看次数

使用 Blazor 使用刷新令牌实现短暂的 Jwt

我们目前正在开发一个Blazor应用程序,该应用程序使用带有刷新令牌的短期(10 分钟)Jwt 进行保护。

目前我们已经实现了 Jwt,并且可以通过 Blazor 服务器端 web api 登录、生成 Jwt 并生成刷新令牌。

从客户端,我使用了以下链接;

使用客户端 Blazor 进行身份验证

并扩展ApiAuthenticationStateProvider.cs如下;

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorage;

    public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
    {
        _httpClient = httpClient;
        _localStorage = localStorage;
    }
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var savedToken = await _localStorage.GetItemAsync<string>("authToken");
        var refreshToken = await _localStorage.GetItemAsync<string>("refreshToken");

        if (string.IsNullOrWhiteSpace(savedToken) || string.IsNullOrWhiteSpace(refreshToken))
        {
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        }

        var userResponse = await _httpClient.GetAsync<UserModel>("api/accounts/user", …
Run Code Online (Sandbox Code Playgroud)

c# jwt blazor blazor-client-side

4
推荐指数
1
解决办法
3485
查看次数

以编程方式在材料自动完成中选择项目

我有一个mat-autocomplete页面,我们将以前使用的值存储在 localStorage 中。如果本地存储中存在该项目,我需要能够设置mat-autocomplete加载值,但不确定如何执行此操作?

我的自动完成的 html 是;

<input type="text" placeholder="Select a trade" aria-label="Select a trade" matInput [formControl]="tradeCtrl" [matAutocomplete]="auto" required>
<mat-error *ngIf="tradeCtrl.invalid">You must enter a trade.</mat-error>
<mat-autocomplete #auto="matAutocomplete" md-menu-class="autocomplete">
    <mat-option *ngFor="let option of filteredCategoryOptions | async" [value]="option.name" (onSelectionChange)="onTradeSelected($event, option)">
        <span [innerHTML]="option.name | highlight: toHighlight"></span>
    </mat-option>
</mat-autocomplete>
Run Code Online (Sandbox Code Playgroud)

那么 component.ts 是;

 ngOnInit() {

        this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {

            this.categoryOptions = categories;

            this.filteredCategoryOptions = this.tradeCtrl.valueChanges
                .pipe(
                startWith(''),
                map(options => options ? this.categoryFilter(options) : this.categoryOptions.slice())
            );

            //bool whether we populate from …
Run Code Online (Sandbox Code Playgroud)

angular-material angular

3
推荐指数
1
解决办法
3085
查看次数

ng2-pdf-viewer 与 Angular 6 'pdf-viewer' 不是已知对象

我正在尝试将ng2-pdf-viewer我的 Angular 6 应用程序与 webpack 集成。

我已按照此处添加模块的说明进行操作;

ng2-pdf-查看器说明

因此,该条目被添加到我的包.json中,如下所示;

{
  "name": "myApp",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "start": "concurrently \"webpack-dev-server --env=dev --open --hot --inline --port 8080\" \"dotnet run\" ",
    "node-sass": "npm rebuild node-sass",
    "webpack-dev": "webpack --env=dev",
    "webpack-production": "webpack --env=prod",
    "build-dev": "npm run webpack-dev",
    "build-production": "npm run webpack-production",
    "watch-webpack-dev": "webpack --env=dev --watch --color",
    "watch-webpack-production": "npm run build-production --watch --color",
    "publish-for-iis": "npm run build-production && dotnet publish -c Release",
    "test": "karma start",
    "test-ci": "karma start --single-run --browsers ChromeHeadless",
    "lint": …
Run Code Online (Sandbox Code Playgroud)

typescript webpack angular angular6

3
推荐指数
1
解决办法
1万
查看次数

发布 ASP.NET 核心时 Serilog 不记录

我将 Serilog 配置为在具有 ASP.NET 核心(运行 Core 2.1)的 WebApi 上写入 MSSQL 表和文件(以尝试确定发生了什么)。

startup.cs按如下方式添加 Serilog 日志;

public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var log = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.MSSqlServer(
            DbGlobals.DevDatabase, "Logs", schemaName:DbGlobals.SchemaName)
        .WriteTo.File("Logs\\Serilog\\log.txt", rollingInterval: RollingInterval.Day)
        .CreateLogger();

    loggerFactory.AddSerilog(log);
Run Code Online (Sandbox Code Playgroud)

其中DbGlobals.DevDatbaseDbglobals.SchemaName是从配置中读取的字符串。

更新作为参考,这些值是;

DbGlobals.Schema = "MySchema";
DbGlobals.DevDatabase = "Data Source=xx.xx.xx.xx;Initial Catalog=DevDatabase;Integrated Security=False;Persist Security Info=False;User ID=LOGIN;Password=PASSWORD;MultipleActiveResultSets=true;";
Run Code Online (Sandbox Code Playgroud)

当使用 IIS Express 在本地运行并在两者debugrelease配置下运行时,两个日志记录功能都可以正常工作。例如在我的控制器中;

public class ReviewPublicController : Controller
{
    private readonly IReviewService _service;
    private readonly IMapper …
Run Code Online (Sandbox Code Playgroud)

c# serilog asp.net-core-webapi asp.net-core-2.1

3
推荐指数
1
解决办法
8533
查看次数