10

I have problem. Locally everything works fine but in the production server it always throws exception 'Response is not available in this context'. What can be the problem? I've noticed that a lot of people experience this problem due to some changes of global.asax. Here is the code of global.asax, the part related to application start.

    protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
        Application["SystemUser"] = TUser.GetUserByIdentifier("system").UID;
        InitializeSolrInstances();
        SearchIndexer.DoIndex();
        StartRatingTimer();
        SolrManager.RecalculateMostRequested();
    }

    private static void InitializeSolrInstances() {
        SolrConfigurationManager.InitSolrConnection<OfferItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/offer");
        SolrConfigurationManager.InitSolrConnection<SavedQueryItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/savedquery");
        SolrConfigurationManager.InitSolrConnection<TopProductsPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topproducts");
        SolrConfigurationManager.InitSolrConnection<TopSellersPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topsellers");
        SolrConfigurationManager.InitSolrConnection<MostRequestedItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/mostrequested");
        SolrConfigurationManager.InitSolrConnection<MostRequestedQuery>(Resources.ApplicationResources.SolrServiceURL + "/requestedquery");
    }

    private void StartRatingTimer() {
        _LastRatingRenewedTime = DateTime.Now;
        DateTime CurrentTime = DateTime.Now;
        DateTime StartTime = new DateTime(2011, 1, 1);
        GlobalSettings.ReIndexMainSolrCores(StartTime, CurrentTime);
        Timer OfferAndUserRatingRenewerTimer = new Timer() {
            /*Timer interval for 24 hours*/
            Interval = 24 * 60 * 60 * 1000, Enabled = true };
        OfferAndUserRatingRenewerTimer.Elapsed += new ElapsedEventHandler(OfferAndUserRatingRenewerTimer_Elapsed);
    }
    public void OfferAndUserRatingRenewerTimer_Elapsed(Object Sender, ElapsedEventArgs e) {
        GlobalSettings.ReIndexMainSolrCores(_LastRatingRenewedTime, e.SignalTime);
        _LastRatingRenewedTime = e.SignalTime;
    }

I do not use Response or Request properties of HttpContext at all. Neither in global asax itself, nor within the methods to be called. Help me.

That what it shows. ` Server Error in '/' Application.

Response is not available in this context.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Response is not available in this context.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): Response is not available in this context.]
   System.Web.Util.HttpEncoder.get_Current() +11406684
   System.Web.HttpUtility.UrlEncode(String str, Encoding e) +137
   SolrNet.Impl.SolrConnection.<Get>b__0(KeyValuePair`2 input) +89
   SolrNet.Utils.<Select>d__1a`2.MoveNext() +612
   SolrNet.Utils.Func.Reduce(IEnumerable`1 source, TResult startValue, Accumulator`2 accumulator) +393
   SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters) +908
   SolrNet.Impl.SolrQueryExecuter`1.Execute(ISolrQuery q, QueryOptions options) +195
   SolrNet.Impl.SolrBasicServer`1.Query(ISolrQuery query, QueryOptions options) +176
   SolrNet.Impl.SolrServer`1.Query(ISolrQuery query, QueryOptions options) +176
   TebeComSearchEngine.SolrManager.RecalculateMostRequested() in SolrManager.cs:77
   TebeCom.MvcApplication.Application_Start() in Global.asax.cs:101

[HttpException (0x80004005): Response is not available in this context.]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4043621
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375

[HttpException (0x80004005): Response is not available in this context.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11612256
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4842149`
Oybek
  • 7,016
  • 5
  • 29
  • 49
  • When does the error occur (when doing what)? Can you show the code where the error occurs? – M4N Jul 08 '11 at 12:14
  • agreed; stacktrace and exact exception details would seem key here – Marc Gravell Jul 08 '11 at 12:36
  • I cannot say what line causes it because I cannot debug the life version. Local version works perfectly! – Oybek Jul 08 '11 at 13:00
  • @Oybek, Darin is correct, this is the reason, now you have to track down the code that is referencing `HttpContext.Current`. With that in mind, what does the call to UrlEncode look like? Its made in `SolrNet.Impl.SolrConnection.b__0(KeyValuePair'2 input)` – Allen Rice Jul 08 '11 at 13:18

3 Answers3

9

'Response is not available in this context'. What can be the problem?

You are running this in IIS7 Integrated Application Pool mode instead of Classic mode. In Integrated mode you don't have access to the HttpResponse in Application_Start any any attempt to access it will blow.

Here's a blog post which covers a similar situation but with the HttpRequest.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Should I switch to a classic mode that I wouldn't like to do, or eliminate the usage of Request that I simply cannot find? – Oybek Jul 08 '11 at 13:32
  • @Oybek, both are possible. Up to you to decide. I would probably eliminate the usage of Request. Maybe you are calling some external library which tries to access the request. Judging from the exception stack trace it seems like it's SolrNet that is trying to access it. – Darin Dimitrov Jul 08 '11 at 13:33
  • @Oybek we can help you find it, we just need to see a little bit more code. Its probably nested somewhere relatively deep. – Allen Rice Jul 08 '11 at 13:34
  • @Oybek I didnt realize SolrNet was a library. I'll look through that code for you. What version are you using? – Allen Rice Jul 08 '11 at 13:59
  • @Allen, I'm using version 3.1 – Oybek Jul 08 '11 at 14:17
  • @Darin SolrNet ends up using `System.Net.WebRequest` to make request(s) in app start. Is that not allowed in Integrated mode now? – Allen Rice Jul 08 '11 at 14:36
  • @Darin heh, looks like you already ran into this http://stackoverflow.com/questions/3881289/asp-net-javascriptserializer-requires-httpresponse check out the call stack. Might be a bug in .Net – Allen Rice Jul 08 '11 at 14:43
  • @Darin I think this should not be a problem at all. Sys.Net.WebRequest is an object which is absolutely independent from the http pipeline. If I'm not mistaken, it can be used from WinForms application where HttpContext absents. – Oybek Jul 08 '11 at 14:44
  • @Oybek I figured it out, its a bug in .net, I'll make a post – Allen Rice Jul 08 '11 at 14:47
  • @Oybek, yes absolutely, the problem has nothing to do with System.Net.WebRequest. It's SolrNet which is trying to call System.Web.Util.HttpEncoder.get_Current() which is coupled to the HttpContext. – Darin Dimitrov Jul 08 '11 at 16:03
5

After a lot of digging and looking around the SolrNet code, they don't appear to be doing anything wrong. Also, as Darin pointed out in an indirect manner, HttpUtility.UrlEncode should work fine in code without a HttpContext, such as a console application, and it does.

However, as VinayC pointed out in his comment on that answer of Darin's:

Actually, it appears to be a bug. From reflector, actual code appears to be "if (null != current && null != current.Response && ...)" where current is current http context. Issue here is that Response getter throws an exception, instead of returning null

Instead of throwing that overly descriptive exception (no doubt they were trying to be helpful), they should have just returned null and let null reference exceptions happen. In this case, they were simply checking for nulls, so the exception wouldn't have happened anyway! I'll report it as a bug if it hasn't been already.

Unfortunately, what this means to you is that you have pretty much no choice but to run in Classic mode. Technically you could put the call to TebeComSearchEngine.SolrManager.RecalculateMostRequested() in a thread that you spawn in application_start and delay its execution until after the app finishes starting. As far as I know, there is no surefire way to programmatically signal the end of the application starting so, that approach may be a little messy.

If you're up for it though, you could probably get that delayed startup mechanism implemented. Compared to punishing the first visitor to the site, it doesn't seem too bad.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Allen Rice
  • 19,068
  • 14
  • 83
  • 115
  • Thanks :) I'll spend some time looking into coming up with a reliable post-app start workaround. It still wouldn't have access to Request, but it would work around .net's bug – Allen Rice Jul 08 '11 at 15:17
  • Well I think, I'll put the code to the Application_BeginRequest with one global boolean. After I launched this code in the routine I'll set the value to false so the subsequent requests will not trigger the code. In other words i'll launch this code on the first page request. – Oybek Jul 08 '11 at 15:28
2

This was discussed about a month ago in the SolrNet mailing list.

It's a regression in ASP.NET 4, here's a mention of this bug.

A future release of SolrNet will replace System.Web.HttpUtility.UrlEncode to work around this bug. (or if you really need this, why not fork the source code and fix it?)

EDIT: I just fixed this.

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275