I've got the following code (lifted from here), and I'm trying to run it on a linux server w/ mono 2.10.5.
private static HttpContext GetCurrentContext(ControllerContext context) {
var currentApplication = (HttpApplication)context.HttpContext.GetService(typeof(HttpApplication));
if (currentApplication == null) {
throw new NullReferenceException("currentApplication");
}
return currentApplication.Context;
}
When running on mono, I get the following exception, which is straightforward enough:
System.NotImplementedException: The requested feature is not
implemented. at System.Web.HttpContextWrapper.GetService
(System.Type serviceType) [0x00000] in <filename unknown>:0
Is there a known workaround I can use to accomplish the same result on mono?
Not sure about the GetService method in Mono but the code you have lifted could be shortened like this:
private static HttpContextBase GetCurrentContext(ControllerContext context) {
return context.HttpContext;
}
You don't really need to go through the Application in order to fetch the HttpContext when you have direct access to it. I have also changed the return type to HttpContextBase instead of HttpContext because in ASP.NET MVC it is recommended to always work with abstractions. It makes your code more weakly coupled and unit testable.
Or if for some unknown to me reason you want to work with an actual HttpContext (no idea why someone would like to tie his code to it) you could try the following:
private static HttpContext GetCurrentContext(ControllerContext context) {
return context.HttpContext.ApplicationInstance.Context;
}
But as you can see in both cases the existence of this GetCurrentContext static method becomes quite questionable.
Related
After updating Blazor from 0.5.1 (with working Flurl) to 0.6.0, calls via flurl throw an exception:
WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method
because it was wiped. See stack trace for details.
The project creates a HttpClientFactory which gets Blazor's HttpClient for being used by Flurl:
Create FlurlClient with Blazor's HttpClient (http) using HttpClientFactoryForBlazor:
IFlurlClient c = new FlurlClient() { Settings = new Flurl.Http.Configuration.ClientFlurlHttpSettings { HttpClientFactory = new HttpClientFactoryForBlazor(http) }};
Use the FlurlClient (c) for example by via Flurl's extensionmethod "IFlurlRequest.WithClient(c);"
private class HttpClientFactoryForBlazor : Flurl.Http.Configuration.IHttpClientFactory
{
private readonly HttpClient httpClient;
public HttpClientFactoryForBlazor(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public virtual HttpClient CreateHttpClient(HttpMessageHandler handler)
{
return this.httpClient;
}
}
So, it seems like this approach does no longer work.
Does anybody know how to make Flurl with Blazor 0.6.0 work?
Call-Stack is:
WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method because it was wiped. See stack trace for details. GET http://srv01.servicegrid.eu:4455/API/Status?forceLoadDbs=False blazor.webassembly.js:1:32098
WASM: at Flurl.Http.FlurlRequest.HandleExceptionAsync (Flurl.Http.HttpCall call, System.Exception ex, System.Threading.CancellationToken token) <0x26945b8 + 0x001c2> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM: at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x005e6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM: at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x0079a> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM: at Flurl.Http.HttpResponseMessageExtensions.ReceiveJson[T] (System.Threading.Tasks.Task`1[TResult] response) <0x26a2180 + 0x000d6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM: at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x000e2> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM: at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x00264> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM: at BlazorCoreDMSTools.CommunicationService.CommunicationService.SetTokenAsync (System.String token, System.String database, System.String serverUri) <0x260dc60 + 0x00d9e> in <cb925648b50340888772566fbaeac465>:0
Just for some background, the Blazor team is in the process of significantly reducing the app's footprint, and resorting to some unusual measures to do so. In a nutshell, they've reduced it by about 20% by "wiping" HttpClientHandler.
wipe means "replace specified method bodies with a single throw
instruction". Doing this (instead of actually removing the method
entirely) means that the assembly retains a completely standard API
surface, and if you try to use one of the wiped methods, you get an
easy-to-understand exception stack trace that tells you which wiped
method you're trying to call.
This is what you've bumped up against: Blazor is still aware of HttpClientHandler for compilation purposes, but will throw a runtime exception if you (or in this case a compatible library) try to use it.
But HttpClient must wrap some implementation of HttpMessageHandler Blazor has its own: BrowserHttpMessageHandler. And Flurl provides an easy way to swap this in via its HttpClientFactory. But you don't need to pass in an HttpClient instance or implement CreateHttpClient. Instead, inherit from DefaultHttpClientFactory and just override CreateMessageHandler:
private class HttpClientFactoryForBlazor : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler()
{
return new BrowserHttpMessageHandler();
}
}
I'd also recommend registering this once globally on app startup, rather than every time you create a FlurlClient:
FlurlHttp.Configure(settings =>
{
settings.HttpClientFactory = new HttpClientFactoryForBlazor();
});
It should also be noted that Blazor is still experimental and that BrowserHttpMessageHandler may be deprecated in a future release, so expect that this could be just a temporary work-around.
Currently in my 3.0 preview 5, BrowserHttpMessageHandler is not there anymore. Here is my current fix by simply not using any HttpMessageHandler. As far as I am aware, no problem happens to me yet, but I am not sure in all use cases:
class BlazorHttpClientFactory : DefaultHttpClientFactory
{
public override HttpClient CreateHttpClient(HttpMessageHandler handler)
{
return new HttpClient();
}
public override HttpMessageHandler CreateMessageHandler()
{
return null;
}
}
I want to write a unit test that verifies my route registration and ControllerFactory so that given a specific URL, a specific controller will be created. Something like this:
Assert.UrlMapsToController("~/Home/Index",typeof(HomeController));
I've modified code taken from the book "Pro ASP.NET MVC 3 Framework", and it seems it would be perfect except that the ControllerFactory.CreateController() call throws an InvalidOperationException and says This method cannot be called during the application's pre-start initialization stage.
So then I downloaded the MVC source code and debugged into it, looking for the source of the problem. It originates from the ControllerFactory looking for all referenced assemblies - so that it can locate potential controllers. Somewhere in the CreateController call-stack, the specific trouble-maker call is this:
internal sealed class BuildManagerWrapper : IBuildManager {
//...
ICollection IBuildManager.GetReferencedAssemblies() {
// This bails with InvalidOperationException with the message
// "This method cannot be called during the application's pre-start
// initialization stage."
return BuildManager.GetReferencedAssemblies();
}
//...
}
I found a SO commentary on this. I still wonder if there is something that can be manually initialized to make the above code happy. Anyone?
But in the absence of that...I can't help notice that the invocation comes from an implementation of IBuildManager. I explored the possibility of injecting my own IBuildManager, but I ran into the following problems:
IBuildManager is marked internal, so I need some other authorized derivation from it. It turns out that the assembly System.Web.Mvc.Test has a class called MockBuildManager, designed for test scenarios, which is perfect!!! This leads to the second problem.
The MVC distributable, near as I can tell, does not come with the System.Web.Mvc.Test assembly (DOH!).
Even if the MVC distributable did come with the System.Web.Mvc.Test assembly, having an instance of MockBuildManager is only half the solution. It is also necessary to feed that instance into the DefaultControllerFactory. Unfortunately the property setter to accomplish this is also marked internal (DOH!).
In short, unless I find another way to "initialize" the MVC framework, my options now are to either:
COMPLETELY duplicate the source code for DefaultControllerFactory and its dependencies, so that I can bypass the original GetReferencedAssemblies() issue. (ugh!)
COMPLETELY replace the MVC distributable with my own build of MVC, based on the MVC source code - with just a couple internal modifiers removed. (double ugh!)
Incidentally, I know that the MvcContrib "TestHelper" has the appearance of accomplishing my goal, but I think it is merely using reflection to find the controller - rather than using the actual IControllerFactory to retrieve a controller type / instance.
A big reason why I want this test capability is that I have made a custom controller factory, based on DefaultControllerFactory, whose behavior I want to verify.
I'm not quite sure what you're trying to accomplish here. If it's just testing your route setup; you're way better off just testing THAT instead of hacking your way into internals. 1st rule of TDD: only test the code you wrote (and in this case that's the routing setup, not the actual route resolving technique done by MVC).
There are tons of posts/blogs about testing a route setup (just google for 'mvc test route'). It all comes down to mocking a request in a httpcontext and calling GetRouteData.
If you really need some ninja skills to mock the buildmanager: there's a way around internal interfaces, which I use for (LinqPad) experimental tests. Most .net assemblies nowadays have the InternalsVisibleToAttribute set, most likely pointing to another signed test assembly. By scanning the target assembly for this attribute and creating an assembly on the fly that matches the name (and the public key token) you can easily access internals.
Mind you that I personally would not use this technique in production test code; but it's a nice way to isolate some complex ideas.
void Main()
{
var bm = BuildManagerMockBase.CreateMock<MyBuildManager>();
bm.FileExists("IsCool?").Dump();
}
public class MyBuildManager : BuildManagerMockBase
{
public override bool FileExists(string virtualPath) { return true; }
}
public abstract class BuildManagerMockBase
{
public static T CreateMock<T>()
where T : BuildManagerMockBase
{
// Locate the mvc assembly
Assembly mvcAssembly = Assembly.GetAssembly(typeof(Controller));
// Get the type of the buildmanager interface
var buildManagerInterface = mvcAssembly.GetType("System.Web.Mvc.IBuildManager",true);
// Locate the "internals visible to" attribute and create a public key token that matches the one specified.
var internalsVisisbleTo = mvcAssembly.GetCustomAttributes(typeof (InternalsVisibleToAttribute), true).FirstOrDefault() as InternalsVisibleToAttribute;
var publicKeyString = internalsVisisbleTo.AssemblyName.Split("=".ToCharArray())[1];
var publicKey = ToBytes(publicKeyString);
// Create a fake System.Web.Mvc.Test assembly with the public key token set
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "System.Web.Mvc.Test";
assemblyName.SetPublicKey(publicKey);
// Get the domain of our current thread to host the new fake assembly
var domain = Thread.GetDomain();
var assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
moduleBuilder = assemblyBuilder.DefineDynamicModule("System.Web.Mvc.Test", "System.Web.Mvc.Test.dll");
AppDomain currentDom = domain;
currentDom.TypeResolve += ResolveEvent;
// Create a new type that inherits from the provided generic and implements the IBuildManager interface
var typeBuilder = moduleBuilder.DefineType("Cheat", TypeAttributes.NotPublic | TypeAttributes.Class, typeof(T), new Type[] { buildManagerInterface });
Type cheatType = typeBuilder.CreateType();
// Magic!
var ret = Activator.CreateInstance(cheatType) as T;
return ret;
}
private static byte[] ToBytes(string str)
{
List<Byte> bytes = new List<Byte>();
while(str.Length > 0)
{
var bstr = str.Substring(0, 2);
bytes.Add(Convert.ToByte(bstr, 16));
str = str.Substring(2);
}
return bytes.ToArray();
}
private static ModuleBuilder moduleBuilder;
private static Assembly ResolveEvent(Object sender, ResolveEventArgs args)
{
return moduleBuilder.Assembly;
}
public virtual bool FileExists(string virtualPath) { throw new NotImplementedException(); }
public virtual Type GetCompiledType(string virtualPath) { throw new NotImplementedException(); }
public virtual ICollection GetReferencedAssemblies() { throw new NotImplementedException(); }
public virtual Stream ReadCachedFile(string fileName) { throw new NotImplementedException(); }
public virtual Stream CreateCachedFile(string fileName) { throw new NotImplementedException(); }
}
I have configured Ninject 2 in an ASP.NET 4.0 project (not MVC) however when I deploy the project to an IIS host it crashes with the following:
System.NullReferenceException: Object reference not set to an instance of an object.
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.PipelineModuleStepContainer.GetEventCount(RequestNotification notification, Boolean isPostEvent) +30
System.Web.PipelineStepManager.ResumeSteps(Exception error) +1481
System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +132
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +709
I have tested this again with a vanilla ASP.net Web Application and get the same crash with the following code:
protected override IKernel CreateKernel()
{
return Container;
}
private IKernel Container
{
get
{
IKernel kernel = new StandardKernel(new SiteModule());
var module = new OnePerRequestModule();
module.Init(this);
return kernel;
}
}
Has anyone else got Ninject working with ASP.net 4?
[UPDATE: 2010.11.03]
After doing some research it appears it may be something to do with the OnePerRequestModule() module, removing this however doesn't seem to resolve the problem I added it due at the suggestion of this question.
In Ninject 2, you use the Ninject.Web extension (see the complete set here) and dont do any explicit config as you have here around OnePerRequestModule etc.
You don't do any web.config stuff either IIRC (I'm using the MVC one and you don't there)
I have a static class with several static methods. In these methods, I'm trying to access the current thread's context using HttpContext.Current. For example:
var userName = HttpContext.Current.User.Identity.Name;
However, when I do that, I receive a NullReferenceException, the infamous "Object reference not set to an instance of an object."
Any ideas?
It isn't clear from the original post that the HttpContext is actually what's missing. The HttpContext.User property can also be null at certain stages of the lifecycle, which would give you the exact same exception. All other issues aside, you need to step through the source and see which part of the expression is actually null.
When you write code that references static methods/properties like HttpContext.Current, you have to write them knowing that your code isn't guaranteed to be run when the methods/properties are actually available. Normally you have something like this:
static string GetCurrentUserName()
{
HttpContext context = HttpContext.Current;
if (context == null)
return null;
IPrincipal user = context.User;
if (user == null)
return null;
return user.Identity.Name;
}
Although I suspect that this wouldn't really solve your problem here, it would just get rid of the exception. The issue is more likely that you're calling this method at a time or place when the context is simply not available, such as on a background thread, static constructor or field initializer, or in the Application_BeginRequest method, or some similar place.
I might start by changing the static methods to instance methods of a class that depends on an HttpContext instance (i.e. taken in the constructor). It's easy to fool yourself into thinking that methods like GetCurrentUserName are simple "utility" methods, but they're really not, and it is generally invalid to be invoking a method that references HttpContext.Current through the static property from any place where you don't already have an instance reference to the same HttpContext (i.e. from the Page class). Odds are, if you start rewriting your classes like this:
public class UserResolver
{
private HttpContext context;
public UserResolver(HttpContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
public string GetUserName()
{
return (context.User != null) ? context.User.Identity.Name : null;
}
}
...then you will likely find out very quickly where the chain is being broken, which will be the point at which you need to reference HttpContext.Current because you can't get it from anywhere else.
In this specific case, obviously, you can solve the problem just by taking the stack trace of the NullReferenceException to find out where/when the chain begins, so you don't have to make the changes I've described above - I'm simply recommending a general approach that will help reduce these sorts of "missing singleton" errors in the future.
I've run into this a few times, especially with static methods in another library and not my main project. I've resorted to passing the HttpContext to the static method as a param when nothing else seems to work.
Where exactly is the null exception being thrown? Have you debug and see what is null? Is the HttpContext.Current is null or the User?
The Description I had a legacy type that is HttpRequestScoped and a legacy web service consuming that service. To resolve services in legacy concerns, I have a global resolver. This was all working well in 1.4, and now that I'm using 2.1.12 I'm experiencing DependencyResolutionException.
The Code In 2.1.12, my Global.asax.cs:
builder.Register(c => new SomeLegacyType(HttpContext.Current)) // note: it relies on HttpContext.Current
.As<SomeLegacyType>()
.HttpRequestScoped();
_containerProvider = new ContainerProvider(builder.Build()); // this is my app's IContainerProvider
Setup.Resolver = new AutofacResolver(_containerProvider.ApplicationContainer);
Setup.Resolver is a singleton, and it is being set to AutofacResolver which looks something like this:
public class AutofacResolver : IResolver
{
private readonly IContainer _container;
public AutofacResolver(IContainer container)
{
_container = container;
}
public TService Get<TService>()
{
return _container.Resolve<TService>();
}
}
The web service looks like this:
[WebService]
public LegacyWebService : WebService
{
[WebMethod(EnableSession=true)]
public String SomeMethod()
{
var legacyType = Setup.Resolver.Get<SomeLegacyType>();
}
}
The Exception The following exception when Setup.Resolver.Get<SomeLegacyType>() is called:
Autofac.Core.DependencyResolutionException: No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[SomeAssembly.SomeLegacyType,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.
at Autofac.Core.Lifetime.MatchingScopeLifetime.FindScope(ISharingLifetimeScope mostNestedVisibleScope)
at Autofac.Core.Resolving.ComponentActivation..ctor(IComponentRegistration registration, IResolveOperation context, ISharingLifetimeScope mostNestedVisibleScope)
at Autofac.Core.Resolving.ResolveOperation.Resolve(ISharingLifetimeScope activationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.Resolve(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Container.Resolve(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.TryResolve(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)
Side Question Is there a better way to have properties injected in ASMX, the same way my ASPX pages are injected (rather than use Setup.Resolver)? I use the AttributedInjectionModule because of legacy concerns. It doesn't appear that the module works on ASMX.
If you configure your 'resolver' to use the RequestLifetime rather than ApplicationContainer all should work as expected.
This means your IContainer parameter will have to change to ILifetimeScope.
I'm not sure about a better way to inject ASMX dependencies, there may be one but I don't think Autofac supports it.