小编Jam*_*ees的帖子

.Net Core Web Api Key

我正在开发一个用户可以通过用户名和密码进行身份验证的应用程序,我们提供了一个JWT令牌,然后在服务器上进行验证.

我想补充的一件事是能够拥有一个特殊的API密钥(guid),用户可以在与此应用程序集成时使用,而不是使用用户名和密码.

我不确定如何做到这一点,因为身份验证部分似乎是一个黑盒子(使用Aspnet身份).

以下是我的一些身份验证设置代码

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<OmbiContext>(options =>
        options.UseSqlite("Data Source=Ombi.db"));

    services.AddIdentity<OmbiUser, IdentityRole>()
        .AddEntityFrameworkStores<OmbiContext>()
        .AddDefaultTokenProviders();

    services.Configure<IdentityOptions>(options =>
    {
        options.Password.RequireDigit = false;
        options.Password.RequiredLength = 1;
        options.Password.RequireLowercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache cache)
{
    var tokenOptions = (IOptions<TokenAuthentication>)app.ApplicationServices.GetService(
        typeof(IOptions<TokenAuthentication>));

    var ctx = (IOmbiContext)app.ApplicationServices.GetService(typeof(IOmbiContext));

    var tokenValidationParameters = new TokenValidationParameters
    {

        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.Value.SecretKey)),

        RequireExpirationTime = true,
        ValidateLifetime = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity asp.net-core

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

将Nininject MVC与类库一起使用

我对IoC框架很陌生,所以请原谅术语.

所以我所拥有的是一个带有Nininject MVC参考的MVC项目.我的项目中有其他类libarys,例如Domain层,我希望能够在那里使用Ninject框架,但我的所有绑定都在MVC项目NinjectWebCommon.csApp_Start文件夹下:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IHardwareService>().To<WindowsHardwareService>();
    kernel.Bind<IStatusApi>().To<StatusApiController>();
}
Run Code Online (Sandbox Code Playgroud)

目前在我的类库中我使用构造函数注入,但有时我不得不对依赖项进行硬编码:

var service = new WindowsHardwareService();
Run Code Online (Sandbox Code Playgroud)

当我希望能够做到以下几点时:

IKernel kernel = new StandardKernel(.....);
var context = kernel.Get<IHardwareService>();
Run Code Online (Sandbox Code Playgroud)

我没有做以下因为我没有任何模块?我读过的所有文档主要针对的是常规Ninject库而不是MVC版本.

我需要做什么,以及如何将常规Ninject库与MVC版本一起使用?

更新

这是我尝试过的:

这样做的目的是使每个项目都可以加载模块并获得当前注入的接口.

App_Start/NinjectWebCommon.cs(在MVC项目中)

private static void RegisterServices(IKernel kernel)
{
    var modules = new IoCModules();
    var newKernal = modules.GetKernel();

    kernel = newKernal;
}
Run Code Online (Sandbox Code Playgroud)

IoCModules.cs(在Project.Ioc项目中)

public class IoCModules
{
    public IKernel GetKernel()
    {
        var modules = new CoreModule();
        return modules.Kernel;
    }
}
Run Code Online (Sandbox Code Playgroud)

CoreModule.cs(在Project.IoC.Modules项目中)< - …

c# asp.net-mvc ninject ioc-container

17
推荐指数
1
解决办法
1040
查看次数

无法从未打开的数据库创建命令

我搜索了很多,我找不到任何答案.

我正在编写一个Xamarin Forms Mobile应用程序,似乎当我最小化应用程序然后重新打开它或我的一个活动启动时,会抛出以下异常:

SQLiteConnection.CreateCommand (System.String cmdText, System.Object[] ps)
SQLite.SQLiteException: Cannot create commands from unopened database
SQLiteConnection.CreateCommand (System.String cmdText, System.Object[] ps)
TableQuery`1[T].GenerateCommand (System.String selectionList)
TableQuery`1[T].GetEnumerator ()
System.Collections.Generic.List`1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) [0x00062] in :0
Enumerable.ToList[TSource] (System.Collections.Generic.IEnumerable`1[T] source)
AsyncTableQuery`1[T].<ToListAsync>b__9_0 ()
Task`1[TResult].InnerInvoke ()
Task.Execute ()
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

通用存储库(创建Sqlite实例的位置)

public class Repository<T> : IRepository<T> where T : Entity, new()
{
     private readonly SQLiteAsyncConnection _db;

    public Repository(string dbPath)
    {
        _db = new SQLiteAsyncConnection(dbPath);
        _db.CreateTableAsync<T>().Wait();
    }
}
Run Code Online (Sandbox Code Playgroud)

国际奥委会注册

FreshIOC.Container.Register<IRepository<Settings>>(new Repository<Settings>(dbPath)); // FreshIOC is a wrapper around TinyIOC …
Run Code Online (Sandbox Code Playgroud)

.net c# sqlite dependency-injection xamarin.forms

12
推荐指数
2
解决办法
1396
查看次数

电子邮件地址拆分

所以我有一个字符串,我需要用分号分割

电子邮件地址: "one@tw;,.'o"@hotmail.com;"some;thing"@example.com

这两个电子邮件地址都有效

所以我希望List<string>得到以下内容:

  • "one@tw;,.'o"@hotmail.com
  • "some;thing"@example.com

但我目前分割地址的方式不起作用:

var addresses = emailAddressString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => x.Trim()).ToList();
Run Code Online (Sandbox Code Playgroud)

由于多个;字符,我最终得到了无效的电子邮件地址.

我已经尝试了几种不同的方法,如果字符串包含引号然后找到;字符的索引并按照这种方式进行处理,我会尝试下去,但这真的很痛苦.

有没有人有更好的建议?

c#

10
推荐指数
2
解决办法
1254
查看次数

.Net Core Process.Start on Linux

在Linux上运行.Net Core应用程序时遇到以下问题.

这是一个例外:

System.ComponentModel.Win32Exception (0x80004005): Permission denied
   at Interop.Sys.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Int32& lpChildPid, Int32& stdinFd, Int32& stdoutFd, Int32& stderrFd)
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at Ombi.Schedule.Jobs.Ombi.OmbiAutomaticUpdater.<Update>d__18.MoveNext() in C:\projects\requestplex\src\Ombi.Schedule\Jobs\Ombi\OmbiAutomaticUpdater.cs:line 218
Run Code Online (Sandbox Code Playgroud)

这是代码:

var updaterFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
     "TempUpdate", $"Ombi.Updater");

var start = new ProcessStartInfo
{
    UseShellExecute = false,
    CreateNoWindow = true,
    FileName = updaterFile,
    Arguments = GetArgs(settings), // This just gets some command line arguments for the app i am attempting to …
Run Code Online (Sandbox Code Playgroud)

.net linux .net-core

10
推荐指数
1
解决办法
1454
查看次数

以编程方式设置Application Insights检测密钥会引发错误

为了在多个环境中支持Application Insights,我们将按照此帖中的建议以编程方式设置Instrumentation Key.

我们已将<InstrumentationKey>ApplicationInsights.config留空,而是在web.config中添加了一个应用程序设置:

<add key="ApplicationInsightsInstrumentationKey" value="1234-5678-9xxx" />
Run Code Online (Sandbox Code Playgroud)

Application_Start中,我们执行以下操作来设置检测密钥:

var instrumentationKey = ConfigurationManager.AppSettings["ApplicationInsightsInstrumentationKey"];

if (string.IsNullOrWhiteSpace(instrumentationKey))
{
    throw new ConfigurationErrorsException("Missing app setting 'ApplicationInsightsInstrumentationKey' used for Application Insights");
}

TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;

new TelemetryClient().TrackEvent("Application started");
Run Code Online (Sandbox Code Playgroud)

但是,这会产生一个例外,说" TelemetryChannel必须在它发送遥测之前进行初始化 ".

谷歌搜索此异常消息不会产生任何结果,但我想在跟踪事件之前还需要一些其他内容吗?

c# azure azure-web-sites azure-application-insights

9
推荐指数
1
解决办法
7992
查看次数

QueueingBasicConsumer 已弃用。哪个消费者更适合实现RabbitMq .net客户端

在 RabbitMQ .NET 客户端中,QueueingBasicConsumer已弃用。

他们建议EventingBasicConsumer改用。我IQueueingBasicConsumer以与他们相同的方式实现了接口,并且运行良好。

但是,我很好奇为什么不推荐使用它以及为什么我应该使用EventingBasicConsumer?

c# rabbitmq

8
推荐指数
2
解决办法
6517
查看次数

无法满足安全令牌请求,因为关闭TLS 1.0时身份验证失败

所以我试图在我的服务器上关闭TLS 1.0和1.1.当我关闭TLS 1.0时,我的应用程序中出现以下错误:

System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
   at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)
   at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)
Run Code Online (Sandbox Code Playgroud)

启用TLS 1.0后一切正常.

现在,调用该服务的代码使用ServicePointManager以下代码指定TLS 1.2 :ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

另一端的服务正在运行.Net 4.6.2,并没有指定使用的TLS协议ServicePointManager,因此根据我的阅读,它将自动检测在此版本的.net框架中运行时需要哪个TLS协议.

有关绑定的WCF服务的Web.config如下

呼叫配置:

<basicHttpBinding>
    <binding name="MyBinding" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:02:00" sendTimeout="00:02:00"/>
</basicHttpBinding>
<netTcpBinding>
    <binding name="CrossDomainBinding">
          <security mode="Message">
              <message clientCredentialType="Certificate"/>
          </security>
    </binding>
</netTcpBinding>
<client>
    <endpoint address="net.tcp://MyService.svc"
    binding="netTcpBinding" bindingConfiguration="CrossDomainBinding" behaviorConfiguration="CrossDomainBehavior"
    contract="MyContract" name="MyBinding">
        <identity>
            <certificate …
Run Code Online (Sandbox Code Playgroud)

.net c# wcf

8
推荐指数
1
解决办法
695
查看次数

为什么Owin.Hosting.StartOptions需要管理员权限?

我有一个使用Owin的自主功能的应用程序.

该应用程序不需要管理员权限,但是当我使用下面的代码,如果它不是作为管理员,我得到抛出因异常运行"拒绝访问"

var options = new StartOptions
{
    ServerFactory = "Microsoft.Owin.Host.HttpListener"
};
options.Urls.Add("http://+:3579/");

using (WebApp.Start<Startup>(options)) { // ..  } 
Run Code Online (Sandbox Code Playgroud)

我需要提供启动选项,否则我会收到HTTP 503错误(请参阅此处)

这是以普通用户身份运行时的异常(非管理员)

at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuilder builder)
at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext context)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
at PlexRequests.UI.Program.Main(String[] args) …
Run Code Online (Sandbox Code Playgroud)

c# permissions owin

7
推荐指数
0
解决办法
1908
查看次数

X509Store Certificates.Find()间歇性地找不到证书

我有一个MVC Web应用程序的问题,它使用私有证书调用另一个服务.

证书位于我的个人密钥库中,针对当前计算机 - 我曾经winhttpcertcfg将证书的权限授予我的Web应用程序的应用程序池标识.密钥按以下方法加载;

internal bool SetCertificateFromCertStore(string subjectName)
{
    X509Store store = null;
    try
    {
        store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
        if (certs.Count != 1)
        {
            store.Close();
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
            if (certs.Count != 1)
            {
                throw new Exception("Unable to find Certificate");
            }
        }
        _certificate = certs[0];
        return true;
    }
    finally
    {
        if (store != null)
        {
            store.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个代码每次都工作到几周前(4月12日),当时在17:05我注意到ELMAH中第一个出现"无法找到证书"异常的例子.检查应用程序日志,系统仍在处理几乎所有请求,此错误在某些请求上每小时只会出现几次.

我已经阅读了类似的问题,建议实现类似于我已经使用的代码(查询多个商店).Windows证书存储是否存在某种已知问题?也许一个锁定问题?还有另一种方法可以解决这个或明显的问题我在这里做错了吗?

您可以提供的任何帮助都将受到赞赏,因为我已经用尽了一些东西!

c# asp.net-mvc client-certificates certificate-store x509

7
推荐指数
0
解决办法
811
查看次数