269

我有一个控制器操作,可以在本地和生产环境中的 Firefox 和本地 IE 上正常工作,但在生产环境中不能正常工作。这是我的控制器操作:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    decimal OP = landTitleUnitOfWork.Sales.Find()
        .Where(x => x.Min >= calculationViewModel.SalesPrice)
        .FirstOrDefault()
        .OP;

    decimal MP = landTitleUnitOfWork.Sales.Find()
        .Where(x => x.Min >= calculationViewModel.MortgageAmount)
        .FirstOrDefault()
        .MP;

    calculationViewModel.LoanAmount = (OP + 100) - MP;
    calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

    return View(calculationViewModel);
}

这是我在 IE 中得到的堆栈跟踪:

错误。处理您的请求时发生错误。System.Reflection.TargetException:非静态方法需要一个目标。在 System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) 在 System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] 参数, CultureInfo 文化) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) 在 System.Data.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance) 的 BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfoculture) System.Data.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(表达式表达式,1 forMergeOption) at System.Data.Objects.ObjectQuery1.GetResults(Nullable 1 forMergeOption) at System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable 1 source) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source) at LandTitle.Controllers.HomeController.MNRefi() at lambda_method(Closure, ControllerBase , Object[] ) 在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 个参数)在 Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() 在 Castle.DynamicProxy.AbstractInvocation.Proceed() 在 Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation 调用) 在 Castle.DynamicProxy.AbstractInvocation.Proceed() 在Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary``2 参数) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() 在 System.Web.Mvc.Async .AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) 在 System.Web.Mvc.Async。AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.b__20() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult)

4

8 回答 8

552

I think this confusing exception occurs when you use a variable in a lambda which is a null-reference at run-time. In your case, I would check if your variable calculationViewModel is a null-reference.

Something like:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    if (calculationViewModel != null)
    {
        decimal OP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.SalesPrice)
            .FirstOrDefault()
            .OP;

        decimal MP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.MortgageAmount)
            .FirstOrDefault()
            .MP;

        calculationViewModel.LoanAmount = (OP + 100) - MP;
        calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

        return View(calculationViewModel);
    }
    else
    {
        // Do something else...
    }
}
于 2012-12-05T06:48:32.923 回答
40

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

于 2013-10-11T04:26:46.993 回答
14

I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.

于 2014-02-21T22:48:30.717 回答
3

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

于 2018-11-01T12:12:58.293 回答
3

For anyone landing here encountering the error Non-static method requires a target while running MS Test [DynamicData] [DataTestMethod] unit tests, the error is likely caused by not making your static data test scenario collection static, i.e. ensure you have:

public **static** IEnumerable<object[]> MyFakeData => 
        new[]
        {
            new object[] { "Foo" },
            new object[] { "Bar" }
        };

[DynamicData(nameof(MyFakeData))]
[DataTestMethod]
public void DoMyTests(string someData) {...}

It's super annoying to debug, as there's no useful stacktrace

于 2021-07-16T17:36:27.057 回答
2

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

于 2018-09-08T15:27:57.030 回答
1

(This is a simple example about the error)

This error occurred when the Linq query get the Data from DB context while the DB Context matching ID is null. Suppose: We getting the Alumni Information from DB on the basis of Student record (reference table).

var getAlumniData = DBContext.Alumni.Where(a => a.AlumniID == loginHistory.AlumniID)
                      .Select(a => new Alumni
                       {
                          Enrollment = a.Student.Enrollment,
                          RegistrationNo = a.RegistrationNo,
                          Name = a.Name,
                       }).SingleOrDefault();

We get the matching ID from User Login History. If the user login history is null, then the loginHistory. AlumniID is null. So it error asked that the required target is needed.

于 2021-03-19T05:28:16.950 回答
0

This could happen if you are using reflection to GetProperty of an object which is null.

于 2020-07-02T13:27:49.453 回答