2

I have a fairly straightforward MVC5 application with an Oracle Backend which is working fine on Localhost, but having some weird behavior when published to an internal-server. At first I was getting a straight forward 500 - Internal Server Error which I diagnosed by trying to access the site from directly within the server. For some reason, upon publication my Web.Config is getting a second container added.

Present before Publish:

  <membership>
      <providers>
          <remove name="OracleMemberShipProvider"/>
      </providers>
  </membership>
  ....
  <customErrors mode="Off"/>
  ...

After Publishing:

  <membership>
      <providers>
          <remove name="OracleMemberShipProvider"/>
      </providers>
  </membership>
  //....
  <customErrors mode="Off"/>
  <membership>
      <providers>
          <clear />
      </providers>
  </membership>

I'm unsure why this is annoyingly occurring now (did not before), but I have been able to get around this by simply logging onto the server after the Publish completes and removing the duplicate from the Web.Config.

With the above correction, I can successfully load the home view of my application. However, if I click buttons to navigate to any of the simple controller actions (Edit/Create/Delete), I receive: Server Error in '/' Applicaiton. Object reference not set to an instance of an object. Examples include:

  • //projectRedirect/MY_CONTROLLER/Edit/78
  • //projectRedirect/MY_CONTROLLER/Create
  • //projectRedirect/MY_CONTROLLER/Delete

Since the Delete is the simplest, I'll detail it below:

    // GET: MY_Controller/Delete/5
    public async Task<ActionResult> Delete(int? id)
    {
        // Save the current URL (with any Filter Conditions) to return user after operation completes.
        Session["returnURL"] = Request.UrlReferrer.AbsoluteUri;

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MY_MODEL my_Model = await db.MY_MODEL.FindAsync(id);
        if (my_Model == null)
        {
            return HttpNotFound();
        }
        // Set property [OWNER] (ex.) 4 as [OWNER_NAME] (ex.) "SMITH, BOB" - cannot specify on the Grid Component, have to do in Controller.
        my_Model.OWNER = my_Model.Owner_Name;
        return View(my_Model);
    }

    // POST: MY_Controller/Delete/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Delete(int id)
    {
        MY_MODEL my_Model = await db.MY_MODEL.FindAsync(id);
        db.MY_MODEL.Remove(my_Model);
        await db.SaveChangesAsync();
        // return RedirectToAction("Index", "Home");
        var returnURL = (Session["returnURL"] != null) ? Session["returnURL"].ToString() : Url.Action("Index", "Home");
        return Redirect(returnURL);
    }

I had assumed the following line of code might be the culprit (though no issues previously). It simply stores the URL the user currently has (which can have filtering conditions for the data-grid specified):

// Save the current URL (with any Filter Conditions) to return user after operation is completed.
Session["returnURL"] = Request.UrlReferrer.AbsoluteUri;

This line is present in all of my relevant Actions in this case. I tried removing it, but upon doing the Publish/Web.Config modification again, I still receive an error when trying to Navigate to any of the Action Methods, though a with more information for the source error:

  • DELETE - Flags @Html.AntiForgeryToken() found within my @using (Html.BeginForm()) { .... }
  • CREATE - Flags @Html.ValidationMessageFor(Model => model.FIELD8, "", new { @class = "text-danger" })
  • EDIT - Flags @htmal.TextBoxFor(model => model.FIELD16, new { @class = "form-control", @readonly = "readonly" })

Below is my Stack Trace offered with the attempt to move to my DELETE View:

[NullReferenceException: Object reference not set to an instance of an object.]
   Project.Controllers.<Delete>d__29.MoveNext() +163
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +143
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +23
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +32
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +231
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Anyone know how to fix this? I have thoroughly racked my brain, but am at a loss as to why this is happening all of a sudden or how to fix it.


EDIT:

So after a lot of testing, I now have some new information (but no real answer). Things I still do not know:

  • Why the extra >membership< is being added to my Web.Config upon Publish (annoying, but can be modified on the Server after Publish to fix).

Regarding new information, I have confirmed that all other posted issues seem to be in relation to my use of a Session Variable.

  • When I have the following code line uncommented in my Edit/Delete/Create Controller Actions - Session["returnURL"] = Request.UrlReferrer.AbsoluteUri; - I am given a flat Server Error in '/' Application. Object reference not set to an instance of an object as mentioned before when attempting to load any of my Edit/Delete/Create Views.
  • Investigating my Views, I figured out that all my Views WILL load if I also comment out the following on each of them - @*<a href="@Session["returnURL"].ToString()"><span class="btn btn-default">Back to List</span></a>*@ - from the below code segment:

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            @*@Html.ActionLink("Back to List", "Index", new { controller = "Home" }, new { @class = "btn btn-default" })*@ 
            @*<a href="@Session["returnURL"].ToString()"><span class="btn btn-default">Back to List</span></a>*@ |
            <input type="submit" value="Save" class="btn btn-primary" />
        </div>
    </div>
    

Does anyone have any thoughts to reason my Published server would not like my use of this Session variable (but localhost handles fine) OR an alternative work around which I could try? This particular value is important to ensure after an action completes, that my User is then returned to the main View's URL (which has any/all specified filtering specified within the URL for the data-grid).

tereško
  • 58,060
  • 25
  • 98
  • 150
Analytic Lunatic
  • 3,853
  • 22
  • 78
  • 120

2 Answers2

1

I finally found some answers. First off I discovered that I was getting extra code in the Web.config after app deployment because of some Insert code specified for the Web.Release.Config:

    <!--<membership xdt:Transform="Insert">
      <providers>
        <clear/>
      </providers>
    </membership>
    <roleManager xdt:Transform="Insert">
      <providers>
        <clear/>
      </providers>
    </roleManager>-->

Commented out the Inserts and now no need to manually modify Web.config after publication.

Next I found the answer in this post (The Session object is null in ASP.NET MVC 4 webapplication once deployed to IIS 7 (W 2008 R2)) to my receiving NullReferenceException when trying to access my Session["variables"]; I simply modified my <modules> section to do an add/remove of the below specified values:

  <configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

I'm still not entirely sure WHY this is the answer, but it worked for my issue in this case.

Analytic Lunatic
  • 3,853
  • 22
  • 78
  • 120
0

A NullReferenceException is a runtime error that generally has to do with a class instance resolving to null unexpectedly.

Nothing in the posted code is jumping out at me as a possible culprit, but the error may be in your views, a child action, your layout, etc. Just because it happens during the run of the Delete action doesn't mean it's necessarily in that action. It just means that some bit of code that runs during the process of returning a result from this action raises this exception. Unfortunately, one of the downsides of async is that it tends to mask the source of the problem, especially for runtime errors.

Look for instances where you're querying a database, using nullable value types (int?, string, etc.), or resolving something from a dynamic like ViewBag or Session. Again, your use of Session in the posted code is fine, as you're doing proper null-checking there, but there may be some other instance elsewhere where you're not.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Thanks for the reply Chris (and as always the well thought out answer). I have posted some more information in my Edit above; it would seem all issues are surrounding my Session variable? – Analytic Lunatic Jul 10 '15 at 14:06