C# 非静态字段、方法或属性“System.Web.Mvc.Controller.HttpContext.get”需要对象引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18977087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:46:16  来源:igfitidea点击:

An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'

c#asp.net-mvc-3

提问by blue

I am getting this error in my MVC3 Application. Please Help...

我在 MVC3 应用程序中收到此错误。请帮忙...

Error :

错误 :

An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'

An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'

On Line:

在线的:

string desigId = HttpContext.Current.Session["Desig_Id"].ToString();

string desigId = HttpContext.Current.Session["Desig_Id"].ToString();

the code with its method in class:

类中的代码及其方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;
using System.Net.Mail;
using System.Net;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;

namespace ApricaCRMEvent.Controllers
{
    public class NotificationController : Controller
    {
        //to send email notification
        [Authorize]
        public static string SendEmailNotification(int crmId, string username, string action)
        {

              string desigId = HttpContext.Current.Session["Desig_Id"].ToString();
        }
    }
}

采纳答案by Dennis

Your base class Controlleralready implements a property HttpContext.

您的基类Controller已经实现了一个属性HttpContext

You can either reference it fully qualified: System.Web.HttpContext.Current...or use the Property of your controller, just like HttpContext.Session. For the second option, your method must be non-staticthough.

您可以引用它完全限定:System.Web.HttpContext.Current...或使用您的控制器的属性,就像HttpContext.Session. 对于第二个选项,您的方法必须是non-static

回答by Mohammed Dawood Ansari

One more reason for the error is that you can't use HttpContext.Current.Sessionand Server.MapPath()in static method

错误的另一个原因是您不能在静态方法中使用HttpContext.Current.SessionServer.MapPath()

In such case you can make use of HostingEnvironment.MapPath()

在这种情况下,您可以使用 HostingEnvironment.MapPath()