如果我从项目中删除DI lib,使用owin,webapi,mvc和DI(SimpleInjector)的新asp.net mvc项目运行正常.然而,一旦推出,在注册DI的OWIN组件时应用程序就会爆炸.OWIN启动配置正在被命中并且运行没有错误,但是当需要注册依赖项时(如下所示),我收到以下错误:
Microsoft.Owin.Host.SystemWeb.dll中出现"System.InvalidOperationException"类型的异常,但未在用户代码中处理
附加信息:在上下文中找不到owin.Environment项.
SimpleInjector注册码:
container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>());
container.RegisterPerWebRequest<HttpContextBase>(() => new HttpContextWrapper(HttpContext.Current));
// app fails on call to line below...
container.RegisterPerWebRequest(() => container.GetInstance<HttpContextBase>().GetOwinContext());
container.RegisterPerWebRequest(() => container.GetInstance<IOwinContext>().Authentication);
container.RegisterPerWebRequest<DbContext, ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
更新 - 完整堆栈跟踪
在WebApplication1.App_Start.SimpleInjectorInitializer的System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase context)中.<> c__DisplayClass6.b__2()在b:\ temp\WebApplication1\WebApplication1\App_Start\SimpleInjectorInitializer.cs:第41行在lambda_method(Closure)at SimpleInjector.Scope.CreateAndCacheInstance [TService,TImplementation](ScopedRegistration
2 registration) at SimpleInjector.Scope.GetInstance[TService,TImplementation](ScopedRegistration2 registration),位于SimpleInjector.Scope.GetInstance [TService,TImplementation](ScopedRegistration2 registration, Scope scope) at SimpleInjector.Advanced.Internal.LazyScopedRegistration2.GetInstance(范围范围),位于SimpleInjector.InstanceProducer.GetInstance()的lambda_method(Closure)
我需要create方法,如果我不知道旧密码,可以在数据库中更改密码.例如,我有下一个代码:
      public IHttpActionResult ChangePassword(ChangePasswordBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var result = UserManager.ChangePassword(User.Identity.GetUserId(), model.OldPassword,
            model.NewPassword);
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }
        return Ok();
    }
Run Code Online (Sandbox Code Playgroud)
在此代码中需要"model.OldPassword"但用户不知道旧密码.我只有密码和当前用户ID.
我正在尝试使用类似...的内容登录用户。
        var accessor = HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
        var result = await accessor.CreateUserIdentityAsync(new User() { ... });
        AuthenticationManager.SignIn(
            new AuthenticationProperties { AllowRefresh = false, IsPersistent = false },
            result);
Run Code Online (Sandbox Code Playgroud)
和登入工作,但如果我刷新页面,用户通过身份认证,在那里我会希望被注销的用户,因为我同时设置AllowRefresh并IsPersistent为false。我错过了一些明显的东西吗?或者也许是一些不明显的东西?(如果它有所作为,则登录的“用户”实际上并不存在,它是一种匿名的经过身份验证的用户)。
我发现很多线程正在讨论这个问题,但是到目前为止,让它们中的任何一个都无法工作.
我一直在尝试关注ProDinner,以此来学习如何在我的应用中实现基于角色的身份验证.但我无法解决我所缺少的问题.我每次尝试登录都会得到
在上下文中找不到owin.Environment项
经过大量的调试和搜索,我发现这个Startup类没有被调用.我试图通过逐步调试proDinner代码来解决,如何Startup被调用和googled(很多!).我的搜索引导我添加(虽然在proDinner项目中都不存在)
<add key="owin:AutomaticAppStartup" value="Tjs.Startup, Tjs" />
Run Code Online (Sandbox Code Playgroud)
然后
<add key="owin:AutomaticAppStartup" value="Tjs.Web.Admin.Startup, Tjs" />
Run Code Online (Sandbox Code Playgroud)
下面我添加了我认为相关代码的所有内容,但如果我遗漏了任何内容,请告诉我.
AccountController是ProDinner的复制粘贴,添加了无参数构造函数,我无法确定如何在Prodinner项目中传递该参数(可能是问题吗?)
Tjs:解决方案名称
Tjs.Web.Admin:名称空间
Owin包
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net45" />
Run Code Online (Sandbox Code Playgroud)
项目的根源
using Microsoft.Owin;
using Owin;
using Tjs.Web.Admin;
using Tjs.Web.Admin.App_Start;
[assembly: OwinStartup(typeof(Startup))]
namespace Tjs.Web.Admin
{
  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
        OwinConfig.ConfigureAuth(app);
    }
  }
} …Run Code Online (Sandbox Code Playgroud) 我在使用WsFederation AuthenticationMVC Web应用程序时遇到登录循环问题.我用Visual Studio来创建Web应用程序的脚手架和来设置WsFederation的Startup.cs.这会生成以下代码块:
public class Startup
{
    private static string realm = ConfigurationManager.AppSettings["ida:Wtrealm"];
    private static string adfsMetadata = ConfigurationManager.AppSettings["ida:ADFSMetadata"];
    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
        {
            Wtrealm = realm,
            MetadataAddress = adfsMetadata
        });
    }
}
Run Code Online (Sandbox Code Playgroud)
Web应用程序托管在Azure中,ADFS位于内部.
在某些客户端上,当进行登录尝试时,登录页面进入循环,请求新令牌在ADFS服务器上导致以下异常:
异常详细信息:Microsoft.IdentityServer.Web.InvalidRequestException:MSIS7042:同一客户端浏览器会话在最后"7"秒内发出了"6"个请求.请联系您的管理员了解详情
我已经阅读了很多关于StackOverflow的文章,并查看了编写IdentityServer的人提供的各种示例,我尝试了各种配置选项,我无法将问题隔离到特定区域.
从我读到的内容来看,OWIN中间件丢失了对象的上下文,因此令牌"丢失".
我试图实现其他一些在StackOverflow上提供的示例代码但是,我似乎找不到解决方案来解决我的问题或者可能没有正确实现代码.
有任何想法吗?
我想为 API 调用实现自定义加密中间件。首先,我读取请求正文 ( IOwinContext.Request.Body) 和标头 (Encryption-Key & Signature)。然后,我解密请求正文,它给了我纯 json 字符串。现在是棘手的部分:我想将这个 json 写回IOwinContextRequest.Body,以便它可以反序列化为对象,然后作为 Controller 方法的参数传递。这是我所做的:
启动:
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use(typeof(EncryptionMiddleware));
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)
中间件:
public class EncryptionMiddleware : OwinMiddleware
{
    public EncryptionMiddleware(OwinMiddleware next) : base(next)
    {
        //
    }
    public async override Task Invoke(IOwinContext context)
    {
        var request = context.Request;
        string json = GetDecryptedJson(context);
        MemoryStream stream = new MemoryStream();
        stream.Write(json, 0, json.Length);
        request.Headers["Content-Lenght"] = json.Lenght.ToString();
        request.Body = stream;
        await Next.Invoke(context);
    } …Run Code Online (Sandbox Code Playgroud) 我将 AutoFac 设置为与 MVC 5 中的 ASP.NET Identity 一起使用。表面上似乎一切正常,即用户可以创建帐户并登录。但后来我发现当安全标记更改时用户不会被注销。通过 AspNetUsers 表中的蛮力或用户更改密码并期望在其他浏览器中注销。
这就是我按照这篇非官方文章设置 AutoFac 的方式。
public void Configuration(IAppBuilder app)
{
    var builder = new ContainerBuilder();
    builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerRequest();
    builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
    builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
    builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
    builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
    builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    app.UseAutofacMiddleware(container);
    app.UseAutofacMvc();
    ConfigureAuth(app);
}
Run Code Online (Sandbox Code Playgroud)
这就是我设置 cookie 身份验证中间件的方式。除了验证间隔更短的时间跨度外,它是默认值。
public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromSeconds(15),
                regenerateIdentity: (manager, …Run Code Online (Sandbox Code Playgroud) 我在我的 Owin 中配置了一个 webApi 和一个静态文件服务器来获取我们在我的应用程序中需要的一些文件。
public void Configuration(IAppBuilder application)
{
   //Other middlewares and configurations
    ....
   application.UseFileServer(new FileServerOptions()
   {
       RequestPath = new PathString("/myPath1/public"),
       FileSystem = new PhysicalFileSystem(m_FolderPathProvider.myPath1FolderPublic)
   });
       // Attribute routing.
            .....
 }
Run Code Online (Sandbox Code Playgroud)
这就像一个魅力。我需要的是为另一个路径和另一个不同的物理文件夹声明另一个 FileServer。我害怕的是,如果我以同样的方式来做,我会覆盖这个,我将只有一个。那么如何声明第二个文件服务器呢?
谢谢你。
我实际上只是通过添加Microsoft.AspNet.WebApi.OwinSelfHost nuget包创建了一个NServiceBus自托管终结点并引导了自托管的Web api 2。一切正常并且运行良好,我可以点击我添加的控制器端点,但是该软件包没有添加诸如web.config之类的常规项。
我想有正常web.config可用的地方,我还可以添加不同的生成配置(如转换文件web.debug.config,web.release.config等等)。
如何将其添加到我的项目中?
我尝试仅添加文件,但ConfigurationManager不读取它。
在我自己的机器和浏览器 (chrome) 中,我无法登录我的网站。它适用于其他浏览器、其他 chrome 用户和隐身窗口。它也适用于我的开发环境或同一网站的其他阶段。
我关于登录的相关代码如下:
=> StartUp.ConfigureAuth
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Data.DbContainer.Entities.User>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});            
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
Run Code Online (Sandbox Code Playgroud)
=> 登录端点
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    SignInStatus result;
    using (var mainDb = MainDbDataManager.GetInstance())
    {
        var user = await mainDb.UserManager.FindByNameAsync(model.Username);
        // Check if user has permission to access …Run Code Online (Sandbox Code Playgroud) owin ×10
c# ×7
asp.net-mvc ×5
asp.net ×2
.net ×1
autofac ×1
cookies ×1
katana ×1
nservicebus ×1