Can't find Request.GetOwinContext - c#

I have been searching for an hour trying to figure out why this isn't working.
I have a ASP.Net MVC 5 application with a WebAPI. I am trying to get Request.GetOwinContext().Authentication, however I can't seem to find how to include GetOwinContext. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TaskPro.Models;
namespace TaskPro.Controllers.api
{
public class AccountController : ApiController
{
[HttpPost]
[AllowAnonymous]
public ReturnStatus Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var ctx = Request.GetOwinContext(); // <-- Can't find this
return ReturnStatus.ReturnStatusSuccess();
}
return base.ReturnStatusErrorsFromModelState(ModelState);
}
}
}
From what I've read, it should be part of the System.Net.Http, but I've included that and it still isn't resolving. Ctrl-Space doesn't give me any intellisense options either.
What am I missing here?

The GetOwinContext extension method is in the System.Web.Http.Owin dll which needs to be downloaded as a nuget package (The nuget package name is Microsoft.AspNet.WebApi.Owin)
Install-Package Microsoft.AspNet.WebApi.Owin
See msdn here: http://msdn.microsoft.com/en-us/library/system.net.http.owinhttprequestmessageextensions.getowincontext(v=vs.118).aspx
Nuget package here: https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Owin
However, the method is still part of the System.Net.Http namespace, so the using definitions you have should be fine.
EDIT
Okay, to clear up some confusion: If you are using an ApiController (i.e MyController : ApiController) you will require the Microsoft.AspNet.WebApi.Owin package.
If you are using a regular Mvc controller (i.e. MyController : Controller) you will need the Microsoft.Owin.Host.SystemWeb package.
In MVC 5 the pipelines for Api and regular MVC were very different, but often have the same naming conventions. So an extension method in one does not apply to the other. Same for a lot of the action filters etc.

None of these worked for me. I had to compare Nuget packages with one that was created with Identity and I found this Nuget package missing which when added fixed the issue for me
Microsoft.Owin.Host.SystemWeb
Apparently you need it to run OWIN on IIS using the ASP.NET request pipeline (read you're screwed without it!)

In WEB API, you can get the reference using the following:
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
it works in Identity 2.0

You may need to add the NuGet package Microsoft.Owin.Host.SystemWeb in order to do this:
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

In my case I need to add
using Microsoft.AspNet.Identity.Owin;
for resolving GetOwinContext and then GetUserManager in following line.
Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

I have this problem and I download extra package from nuget to solve my problem,(run following command in Package Manager Console)
Install-Package Microsoft.Owin.Host.SystemWeb

(Please note that this answer is for ASP.NET Web API which corresponds to the tag used on the question. See this question if your inquiry is with respect to ASP.NET MVC.)
The question does not specify how the ASP.NET Web API service is to be hosted. The dialog in this post indicates (emphasis mine):
kichalla wrote Oct 24, 2014 at 1:35 AM
If you are NOT self-hosting, do not use Microsoft.AspNet.WebApi.Owin
package with IIS...this package is only supposed to be used with self
hosting.
Use of the Microsoft.AspNet.WebApi.Owin package is recommended in the accepted answer. In this answer I am reporting what has worked for me when hosting an ASP.NET Web API service in IIS.
First, install the following NuGet package:
Microsoft.Owin.Host.SystemWeb
OWIN server that enables OWIN-based applications to run on IIS using
the ASP.NET request pipeline.
(Note that as I write, the latest available version of this NuGet package is 3.1.0. Also, to the extent that it might matter, I am using Visual Studio 2013 Update 5.)
After installing this NuGet package, you can do the following:
using Microsoft.Owin;
using System.Web;
IOwinContext context = HttpContext.Current.GetOwinContext();
// or
IOwinContext context = HttpContext.Current.Request.GetOwinContext();
Now, to shed some light on how these statements are resolved. In Visual Studio, if you right-click GetOwinContext in either statement and select "Peek Definition," Visual Studio will display the following:
// Assembly Microsoft.Owin.Host.SystemWeb.dll, v3.1.0.0
using Microsoft.Owin;
using System;
using System.Runtime.CompilerServices;
namespace System.Web
{
public static class HttpContextExtensions
{
public static IOwinContext GetOwinContext(this HttpContext context);
public static IOwinContext GetOwinContext(this HttpRequest request);
}
}
As you can see, within the System.Web namespace, there are two GetOwinContext extension methods:
One on the HttpContext class, and
The other on the HttpRequest class.
Again, for those hosting their Web API service in IIS, my hope is that this clears up any ambiguity regarding where a definition for GetOwinContext can be found with respect to this late date in 2017.

This took me forever to find a simple answer: but what I did was use the Get extension of the single instance of the IOwinContext that was instantiated in the startup. So it came out like this:
private readonly IOwinContext _iOwinContext = HttpContext.Current.GetOwinContext();
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? _iOwinContext.Get<ApplicationUserManager>() ;
}
private set
{
_userManager = value;
}
}

The GetOwinContext() extension method is not found in threads other than the GUI thread.
So be careful to not call this function from within any awaited function.

After looking at the ASP.NET default project I discovered I needed to include this in my application startup:
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in
// with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);`

I was missing package: Microsoft.AspNet.WebApi.Owin for ApiControllers.
Hope this helps!

I had this same problem and solved it by using a private method:
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
This worked swimmingly for me.

I had to add package Microsoft.AspNet.Identity.Owin

Related

Ninject & WebAPI: Getting started after install from NuGet

I installed the NuGet package Ninject Integration for WebApi2 via the Package Manager Console.
According to the wiki on the project's GitHub pages, this should have created a class called NinjectWebCommon in the App_Start folder. But it didn't.
That same GitHub wiki page explains what you should see so that you can add it yourself. So I tried creating the NinjectWebCommon class myself. The problem here is that I can't find the namespace for OnePerRequestModule in the following snippet.
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
The alternative, and according to that GitHub wiki page there's no effective difference between the two, is to modify the global.asax. So I tried this method and added some bindings like so
private void RegisterServices(IKernel kernel)
{
kernel.Bind<IEntityAccess>().To<EntityAccess>();
kernel.Bind<IDictionaryRepository>().To<DictionaryRepository>();
}
and found that my project builds, but when a request is sent to the WebAPI project it can't be found (i.e., I receive a 404 response).
So there's obviously some other piece of necessary wiring up which isn't in my project.
It appears that despite changing my global.asax to derive from NinjectHttpApplication, the global.asax is no longer being called.
Can anyone tell me what I might be missing? I've uninstalled and reinstalled the NuGet package a few times but the NinjectWebCommon class never appears, nor does my global.asax file ever get modified.
I've also read Ninject's own documentation but frustratingly this is a fairly large tutorial covering the basics of IoC and how Ninject operates rather than telling you how to get started with using Ninject.
There's also this SO post asking how to get started with Ninject for WebAPI, so it looks like something's amiss with their NuGet package.
And like that, I've just found the answer: there is an additional NuGet package which must be referenced:
Ninject.Web.WebApi.WebHost
Installing "Ninject integration for WebApi2" package is not sufficient.
This really should be more clearly explained.

app.MapSignalR is not a member of IAppBuilder

I'm getting this error when trying to map SignalR in my Startup.cs class shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MyControl.Webserver.Startup))]
namespace MyControl.Webserver
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
I have read the other question that's asking the same question 'Owin.IAppBuilder' does not contain a definition for 'MapSignalR'. Only difference being that NuGet has correctly installed Added Microsoft.Owin version 2.0.1 and Added Microsoft.Owin.Security version 2.0.1.
I've tried creating another class library just the same. Installing Microsoft.AspNet.SignalR from NuGet and adding the same Startup.cs class. Then it works.
I'm using:
Microsoft.AspNet.SignalR 2.1.1
Microsoft.Owin 2.0.1
Microsoft.Owin.Security 2.0.1
Owin 1.0
I have no idea where to go from here.
Any help is greatly appreciated.
I fixed it by deleting some files stashed away in another folder.
They didn't seem to be referenced anywhere, but they must have been doing something :-)

Issue in Global.asax.cs page in MVC4

I my ASP.NET MVC 4 Project, my Global.asax.cs page shows the error on
WebApiConfig.Register(GlobalConfiguration.Configuration);
The name 'GlobalConfiguration' does not exist in the current context
I have done many controllers and Views and all... How can I solve this issue and recover my project?
Here is the rest of my code for context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace .....
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
Make sure you have assembly System.Web.Http.WebHost.dll referenced. This is where GlobalConfiguration is.
With .NET Framework 4.5.1, GlobalConfiguration is found in System.Web.Http:
PM> Install-Package Microsoft.AspNet.WebApi.WebHost
Update-Package Microsoft.AspNet.WebApi.WebHost -reinstall
This worked for me. I was facing issues with the reference not being updated correctly on Update-package or even removing and installing the package again.
The above command reinstalls all dependencies, and usually does the trick whenever I face nuget package reference issue.
Also try doing the opposite (no offense) to what David Bohunek suggests. I tried Davids suggestion to no avail. Then I would up removing that reference that was referenced directly in the "Assemblies" section.
Then I removed the Web Api 2.2 and Web Api 2.2 Web Host Nugets, performed a clean and then JUST added back the Web Api 2.2 Web Host NuGet.
Try that. Good luck, it worked for me.
in my asp.net webform based on 4.5, adding System.Web.Routing dll and below import in global.aspx resolved the problem
<%# Import Namespace="System.Web.Routing" %>
<%# Import Namespace="System.Web.Http" %>
I attempted most of the fixes listed above to no avail. I am sure 9 out of 10 are normally resolved by the posts above but for this error, but none of these helped me.
My fix for this error, was that I was renaming my namespace and had two different references to the namespace which in the end caused my issue. Since I wanted to update the namespace with something other than I started with, I ended up fixing this issue by changing my namespace to the newer one in my WebApiConfig.cs. Apparently it was one of the last files which I hadn't used the newer namespace name.
Well, once I changed that then my errors went away. Also, another fix for this same issue was to specify using old namespace name; which also fixed it temporarily which got me to just rename it in the WebApiConfig.cs with the new name.
In my case I was getting a similar issue in Glabal.asax:
The name 'AreaRegistration' does not exist in the current context.
I already had System.Web.Mvc namespace in Global.asax.cs but the compiler was somewhat not aware of it, that is, the AreaRegistration class was not being found.
What fixed the issue was executing the following command in Package Manager Console inside Visual Studio:
PM> Update-Package -reinstall
After NuGet reinstalled all the project's packages, the missing class names appeared and the code built successfully.
Something is broken in Visual Studio\NuGet restore pipeline...

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

I have downloaded, and successfully ran the ASP.NET Identity sample from here:
https://github.com/rustd/AspnetIdentitySample
I am now in the middle of implementing the ASP.NET Identity framework in my project and have ran into a problem, that has driven me mad all day...
GetOwinContext() does not exist as an extension method on my HttpContext
I am implementing the identity framework in class library. I have installed all the latest (pre-release version) of the Identity framework and everything - apart from this - is working fine.
I have tried implementing the same code as the same direct in my controller, and find the same problem.
I'm clearly missing a reference somewhere, though I have no idea what..!..
The code-block that is killing me is:
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
I have added references to the following - tried these both in my class library and also direct on the controller, none of them work for me...
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Microsoft.Owin;
using System.Web;
... this is driving me up the wall....any idea?
UPDATE
I have checked the versions of Identity & OWIN in the sample, and I have made sure I have the same versions in my solution.
More so, if I search the object browser on the sample for GetOwinContext I can find the method, however when I search for it in my solution it is nowhere to be found... I must have some library out of date, but I can't find it!
ARGH!
I found it... I didn't have an extra package, called Microsoft.Owin.Host.SystemWeb
Once i searched and installed this, it worked.
Now - i am not sure if i just missed everything, though found NO reference to such a library or package when going through various tutorials. It also didn't get installed when i installed all this Identity framework... Not sure if it were just me..
EDIT
Although it's in the Microsoft.Owin.Host.SystemWeb assembly it is an extension method in the System.Web namespace, so you need to have the reference to the former, and be using the latter.
I believe you need to reference the current HttpContext if you are outside of the controller. The MVC controllers have a base reference to the current context. However, outside of that, you have to explicitly declare you want the current HttpContext
return HttpContext.Current.GetOwinContext().Authentication;
As for it not showing up, a new MVC 5 project template using the code you show above (the IAuthenticationManager) has the following using statements at the top of the account controller:
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using WebApplication2.Models;
Commenting out each one, it appears the GetOwinContext() is actually a part of the System.Web.Mvc assembly.
After trial and error comparing the using statements of my controller and the Asp.Net Template controller
using System.Web;
Solved the problem for me.
You are also going to need to add:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
To use GetUserManager method.
Microsoft couldn't find a way to resolve this automatically with right click and resolve like other missing using statements?
In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.
Make sure you installed the nuget package Microsoft.AspNet.Identity.Owin. Then add System.Net.Http namespace.
Just using
HttpContext.Current.GetOwinContext()
did the trick in my case.
For Devs getting this error in Web API Project -
The GetOwinContext extension method is defined in System.Web.Http.Owin dll and one more package will be needed i.e. Microsoft.Owin.Host.SystemWeb. This package needs to be installed in your project from nuget.
Link To Package: OWIN Package Install Command -
Install-Package Microsoft.AspNet.WebApi.Owin
Link To System.web Package : Package Install Command -
Install-Package Microsoft.Owin.Host.SystemWeb
In order to resolve this error you need to find why its occurring in your case. Please Cross check below points in your code -
You must have reference to Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.Owin;
Define GetOwinContext() Under HttpContext.Current as below -
return _userManager1 ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
OR
return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
Complete Code Where GetOwinContext() is used -
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
Namespace's I'm Using in Code File where GetOwinContext() Is used
using AngularJSAuthentication.API.Entities;
using AngularJSAuthentication.API.Models;
using HomeCinema.Common;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
I got this error while moving my code from my one project to another.
To get UserManager in API
return HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();
where AppUserManager is the class that inherits from UserManager.
I had all the correct packages and usings, but had to built first before I could get GetOwinContext() to work.
Just install this package and your code will work:=>
Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0

Ninject and asp.net MVC4

I have a MVC3 application that I would like to port to MVC4. I am using Ninject for dependency injection. Using Nuget, I added "Ninject" to my project and created a controller factory as shown below
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
//Add ninject bindings here
}
}
This works fine for MVC3 but things have changed in MVC4. I did some digging and found this link that explains how to get ninject working for MVC4
http://haacked.com/archive/2012/03/11/itrsquos-the-little-things-about-asp-net-mvc-4.aspx
However, I am having trouble getting the code in the above link to compile. Specifically, The code that I am supposed to place in the Start() method of the web.common file gives me unresolved namespace errors
GlobalConfiguration.Configuration.ServiceResolver
.SetResolver(DependencyResolver.Current.ToServiceResolver());
Both "ServiceResolver" and ".SetResolver" are unresolved. What references do I need to add to enable these? Also, if possible can you point me towards a tutorial showing me how to get ninject working in MVC4 without having to install the nuget package ninject.mvc3? I ask because I would prefer not to have any packages installed in my application that were written for MVC3 specifically to avoid things from breaking down the line if these nuget packages are updated.
edit: I should have added that I am using Visual studio 2012 and .Net 4.5
Phil's article is about using Ninject with WebAPI. Is that what you mean? You don't need to do that for normal MVC injection. Also, you should be using the Ninject.MVC3 NuGet package with MVC4 (yes, I know it says MVC3, but it still works fine because NuGet sets up Assembly Version Redirects that make everything Just Work), this sets everything up and you don't need a controller factory. Just edit the NinjectWebCommon.cs file to add your bindings.
Just simply Add namespace
Using Ninject;
after installing template from Nuget...
U just install "Ninject" but not "Ninject for MVC3" from Nuget Template

Categories

Resources