标签: owin

为什么[Owin]在新项目上抛出空例外?

我有一个相当奇怪的问题,我不知道如何解决或者我是否能解决它.

我已经对这个问题进行了一些研究,但无法找到导致问题的答案.

我正在http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-并遵循一个相当简单的指南-openid点登录

启用SSL并更改controller为要求https后,我收到以下错误:

'/'应用程序中的服务器错误.

你调用的对象是空的.

描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例.

来源错误:

在执行当前Web请求期间生成了未处理的异常.可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息.

堆栈跟踪:

[NullReferenceException:对象引用未设置为对象的实例.]
Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider.Exception(CookieExceptionContext context)+49
Microsoft.Owin.Security.Cookies.d__2.MoveNext()+3698 System.Runtime .CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()+24 Microsoft.Owin.Security.Infrastructure. d__0.MoveNext()810个System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext()+ 427 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(T 请求任务)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+ 21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()+641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)+93
System. Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()641系统.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.Owin.Host.SystemWeb. IntegratedPipeline.d__5.MoveN EXT()287个System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21微软. Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()+272 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()+22 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()+33 Microsoft.Owin.Host .SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)+150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)+42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&completedSynchronously)+155

版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.34237

关闭SSL修复这个问题,我也知道,注释掉startup.authapp_start修复的问题SSL …

c# nullreferenceexception owin

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

Microsoft在OWIN实现中扩展方法CreatePerOwinContext的目的是什么

我是ASP.NET的新手,目前正在学习ASP.NET身份.我知道它建立在微软的OWIN实现之上,而且我也在学习它.所以,我在Owin启动代码中遇到了扩展方法CreatePerOwinContext,我没有看到使用它的明确目的.它是某种依赖注入容器吗?这个方法的真正目的是什么?在什么情况下应该应用它?

asp.net owin katana

49
推荐指数
2
解决办法
2万
查看次数

使用OAuthBearerTokens与UseOAuthBearerAuthentication

在我们的Startup课程中,我配置了以下auth服务器选项:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/api/v1/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = new SimpleAuthorizationServerProvider()
};
Run Code Online (Sandbox Code Playgroud)

在此之后,我们应该使用哪个选项来实际启用承载身份验证?互联网上似乎有两种变体.

选项1:

app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
Run Code Online (Sandbox Code Playgroud)

选项2:

app.UseOAuthBearerTokens(OAuthServerOptions);
Run Code Online (Sandbox Code Playgroud)

我对它们进行了测试,结果是一样的.

这些选项有什么区别?我们什么时候应该使用哪个?

owin katana asp.net-identity asp.net-web-api2 asp.net-identity-2

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

Hw将参数传递给我自己的Startup类?

我正在尝试使用OWIN开发一个web api自托管应用程序.在我自己的XyzStartup类中,我需要一个外部参数:contentFolderPath.

但是,我没有找到通过这个论点的方法.这是我的代码如下:

var contentFolderPath = this.TextBox.Text; // user input

var startOptions = new StartOptions();
using(WebApp.Start<XyzStartup>(startOptions)){

}
Run Code Online (Sandbox Code Playgroud)

我的创业公司

public class XyzStartup
{
     XyzStartup(string contentFolderPath) {  ...  }
}
Run Code Online (Sandbox Code Playgroud)

我注意到有一个StartOption类,但不知道如何使用它.我可以在XyzStartup类中使用它吗?

提前致谢!


我终于找到了这样做的方法:

var startOptions = new StartOptions();
startOptions.Urls.Add('..some url ..');

WebApp.Start(startOptions, (appBuilder)=>{
    new XyzStartup(contentFolderPath).Configuration(appBuilder);
}
Run Code Online (Sandbox Code Playgroud)

c# owin

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

UseCookieAuthentication与UseExternalSignInCookie

我使用Owin通过Google oAuth进行授权.以下是我的cookie配置方式:

// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Authentication/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Run Code Online (Sandbox Code Playgroud)

所以我正在使用UseCookieAuthentication和UseExternalSignInCookie,这似乎是多余的.我应该为IAuthenticationManager方法(SignIn,SingOUt等)指定这两种AuthenticationType中的哪一种?或者我应该只保留其中一个?

更新.让我最困惑的是SignIn方法:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
Run Code Online (Sandbox Code Playgroud)

所以来自ExternalCookie的注销,但在ApplicationCookie中有迹象.

asp.net-mvc owin

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

如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登录/验证用户?

道歉并提前感谢您提出这个问题!我还是SO的新手.

我一直在使用MVC5,EF6和VS 2013开发Web应用程序.

一旦发布,我花了一些时间升级到RC位.感谢所有伟大的帖子:例如.解耦Microsoft.AspNet.Identity.*并将asp.net MVC从5.0.0-beta2更新到5.0.0-rc1!

在我无限的智慧中,我决定转向@Hao Kung在这里发布的RTM位:我如何能够及早访问即将到来的Asp.Net Identity变化?.我认为当我们最终收到RTM版本时,我会省去麻烦并且不会太落后.

这可能是一场噩梦,或者我只是完全遗漏了某些东西(或两者兼而有之),因为我无法弄清楚曾经使用RC1的基本任务.

虽然我似乎是通过控制器登录用户(Asp.Net Identity RTM版本中的Microsoft.AspNet.Identity.Owin.AuthenticationManager在哪里?)...我的WindowsIdentity始终为空,在我调用SignIn后未经过身份验证.正确填充了user和claimIdentity对象.

这是我调用的操作方法(为了完整性将属性移动到局部变量):

[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public virtual async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid) {
        var userManager = new UserManager<EtdsUser>(new UserStore<EtdsUser>(new EtdsContext()));
        var user = userManager.Find(model.UserName, model.Password);
        if (user != null) {
            var authenticationManager = HttpContext.GetOwinContext().Authentication;
            authenticationManager.SignOut(new[] {DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ExternalBearer});
            var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe}, claimsIdentity);
            return RedirectToLocal(returnUrl);
        }
    }
    ModelState.AddModelError("", "The …
Run Code Online (Sandbox Code Playgroud)

c# owin visual-studio-2013 asp.net-mvc-5 asp.net-identity

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

MVC 5如何使用本地化路由定义Owin LoginPath

我有一个MVC 5网站,其本地化路由定义为

routes.MapRoute(
            name: "Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

默认文化导致的位置"en-US".


启动时出现问题我必须使用LoginPath属性定义登录URL,该属性设置一次并且它将始终使用提供的值,例如默认文化,如果"/ en-Us/Account/Login"是指定值.然后我尝试使用UrlHelper类,希望体验一些魔力,但结果显然是一样的:

var httpContext = HttpContext.Current;
        if (httpContext == null) {
          var request = new HttpRequest("/", "http://example.com", "");
          var response = new HttpResponse(new StringWriter());
          httpContext = new HttpContext(request, response);
        }

        var httpContextBase = new HttpContextWrapper(httpContext);
        var routeData = new RouteData();
        var requestContext = new RequestContext(httpContextBase, routeData);
        UrlHelper helper = new UrlHelper(requestContext);

        var loginPath …
Run Code Online (Sandbox Code Playgroud)

c# owin asp.net-mvc-5

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

在Windows服务中使用OWIN托管WebAPI

我使用OWIN(在Windows服务中)自我托管Web API.据我所知,这足以让HTTP请求进入Windows服务.我可以在http://localhost/users本地(来自同一台机器)点击WebAPI URL(),但不能从其他机器点击.我正在使用端口80,IIS已停止.当IIS运行时,其他网站(在IIS中,在端口80上托管)可以正常工作.

//在Windows服务中:

public partial class Service1 : ServiceBase
{
    ...
    ...

    protected override void OnStart(string[] args)
    {
        Console.WriteLine("Starting service...");
        string baseAddress = "http://localhost:80/";
        WebApp.Start<Startup>(baseAddress);  //This is OWIN stuff.
    }
    ...
    ...
}

public class Startup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        appBuilder.UseWebApi(config); …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api owin

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

ASP.NET(OWIN)标识:如何从Web API控制器获取UserID?

(使用VS2013 RTW,ASP.NET MVC5)

我在使用ASP.NET标识时看到了很多关于如何向ApplicationUser类(和表)添加属性的文档.但是我没有看到任何关于如何通过外键将内容映射到ApplicationUser表的单独表格的文档.

我已经成功地派生了我自己的Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext,现在我自己的"UserPreferences"表与我的SQL Server数据库中的各种"AspNet*"表共存.但我不清楚获取当前用户ID的最佳方法,以便在"UserPreferences"表中写入新行.请注意,该项目是ASP.NET MVC,但我已添加(并且正在使用)Web API控制器.

我有一个有效的解决方案,它是:

            var uman = new Microsoft.AspNet.Identity.UserManager<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(new App1.Data.App1DbContext()));

            var uident = User.Identity;

            var userobject = uman.FindByNameAsync(uident.Name);

            var userid = userobject.Result.Id;
            // (Perform new row creation including the userid we just looked up
Run Code Online (Sandbox Code Playgroud)

考虑到AspNetUsers表(由Identity框架定义)包含以下字段:

-id (PK, nvarchar(128) - seems to contain a GUID, not sure why not an autoincrement integer, but I assume there are reasons for this)
-Username (nvarchar(max))
-PasswordHash (nvarchar(max))
-SecurityStamp (nvarchar(max))
Run Code Online (Sandbox Code Playgroud)

我认为id字段(不是用户名)是此表中引用的正确字段.(我当时认为用户可能会更改他/她的用户名,然后其他人就可以假设其他用户的用户名,这就是为什么两个字段都可能存在的原因.)那么,我需要获取当前用户的存储空间ID. "UserPreferences"表,这是上面的代码所做的.但是,进行此查找似乎效率低下.

重要的一点是,在System.Web.Mvc.Controller的上下文中,我可以这样做:

User.Identity.GetUserId()
(Runtime type of User.Identity: System.Security.Principal.GenericIdentity) …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc asp.net-web-api owin visual-studio-2013 asp.net-identity

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

ASP.NET MVC 5 Web.config:"FormsAuthenticationModule"或"FormsAuthentication"

好吧,这不是什么大不了的事,但它让我烦恼,我不能放手.

所以我使用MVC 5.1与.NET 4.5.1和OWIN身份验证.因此,当您创建新的MVC 5项目时,以下内容会自动添加到Web.config中以删除表单身份验证http模块,因为在使用OWIN中间件时不再需要它:

<system.webServer>
    <modules>
        <remove name="FormsAuthenticationModule" />
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

现在,因为我们正在删除模块,这意味着它之前已添加,所以这里是注册此http模块的条目C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config:

<httpModules>
    <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</httpModules>
Run Code Online (Sandbox Code Playgroud)

这里是C:\Windows\System32\inetsrv\config\applicationHost.configIIS 8.5 的条目,告诉我的应用程序使用该模块:

<system.webServer>
    <modules>
        <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

因此,在应用程序级别自动添加到我的Web配置的名称属性为"FormsAuthenticationModule",而两个服务器级别/ asp.net级别配置文件中的条目使用名称属性"FormsAuthentication".那么这里发生了什么?在我看来,由于name属性不匹配,因此不会删除该模块.我只是认为这是一个错字,但在网上搜索后,每个人似乎都在应用程序web.config中使用"FormsAuthenticationModule".这是最新版本的asp.net/iis的最新变化还是我错过了什么?

asp.net forms-authentication iis-8 owin asp.net-mvc-5

43
推荐指数
2
解决办法
2万
查看次数