问题WebMethod是静态在C#ASP.NET Codebehind [英] Issue with WebMethod being Static in C# ASP.NET Codebehind

查看:158
本文介绍了问题WebMethod是静态在C#ASP.NET Codebehind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在单个页面上有多个表单导致的问题,我使用AJAX调用WebMethod提交表单而不是使用ASP控件。但是,在这样做时,以前用于在我的数据库中创建新条目的方法不再有效,因为WebMethod必须是静态的。



我已经验证了我的用户已经使用ASPX身份验证,并尝试使用codebehind检索该用户的用户名和ID。用户已经在Page_Load上进行了身份验证,但似乎我无法通过我的WebMethod访问这些信息。这是否可以在静态WebMethod内做?谢谢你提前的帮助!

  [WebMethod] 
public static void CreateJob()
{
Submit_Job();
}

public static void Submit_Job()
{
if(Page.User.Identity.IsAuthenticated)
{
try
{
string username = Context.User.Identity.Name;
}
catch
{
Context.GetOwinContext()。Authentication.SignOut();
}
}

var manager = new UserManager();
var usernameDatabase = new ApplicationUser(){UserName = username};
usernameDatabase = manager.Find(username,password here);
if(usernameDatabase!= null)
{
IdentityHelper.SignIn(manager,usernameDatabase,isPersistent:false);

string jobTitle = Request.Form [jobTitle];

using(var ctx = new CreateUserContext(ConfigurationManager.ConnectionStrings [myconnectionstring]。ConnectionString))
{
Job job = new Job()
{
job_title = jobTitle
};

ctx.Jobs.Add(job);
ctx.SaveChanges();
}
}
}

编辑:
有例如Page.User.Identity.IsAuthenticated - 页面,上下文和请求都出现错误,它们不能是静态的。



具体错误:
(非静态字段,方法或属性Control.Page需要一个对象引用)

解决方案

从简单的评论移动



幸运的是,每当用户登录我们的应用程序时,我们将加密的用户信息存储到会话变量中,因此我检索到该信息,传递给我们它给我们的用户的类构造函数,它解密它,我可以使用我的登录用户信息而不用麻烦。



所以,我的解决方案是将用户信息存储在会话,但要小心,你存储。可能会将用户对象序列化并存储在会话中,然后,无论何时需要它

  public void Page_Load()
{
//检索经过身份验证的用户信息
UserClass userObject = GetUserCredentials();
//调用将经过身份验证的用户对象转换为包含用户会话信息的字符串的方法。鉴于这些信息的敏感性,可能想要尝试加密它或使其反复。将其存储在会话变量中作为字符串
会话[UserContext] = userObject.SerializeUser()
/ *页面代码的其余部分在此处* /
}

[WebMethod(EnableSession = true)]
public static void CreateJob()
{
Submit_Job();
}

public static void Submit_Job()
{
//允许通过会话变量获取经过身份验证的用户信息。由于方法的静态特性,我们无法直接访问Session变量,所以我们使用当前的HttpContext
string serializedUserInfo =)HttpContext.Current.Session [UserContext]来调用它。ToString();

//让我们创建用户对象。在我的情况下,我们有一个过多的构造函数,它接收用户的序列化/加密信息,对其进行解析,反序列化,并使用反序列化信息返回类的实例
UserClass userObject = new UserClass(s​​erializedUserInfo);
//做任何方法现在要做的!
}

关于序列化的主题,使用c#对象序列化会带给你几场好的比赛。 XML和JSON是最常用的两种序列化,特别是Web方法。二进制序列化也是模糊登录用户的信息


的好选择

Due to a problem caused by having multiple forms on a single page, I used an AJAX call to a WebMethod to submit my form instead of using ASP controls. However, in doing this, the previous method I had used to create a new entry into my database no longer works because a WebMethod must be static.

I have authenticated my user already using ASPX authentication, and am trying to retrieve the username and ID of that user with codebehind. The user has already been authenticated on Page_Load, but it seems I cannot access this information through my WebMethod. Is this possible to do inside of a static WebMethod? Thank you for all of your help in advance!

[WebMethod]
public static void CreateJob()
{
    Submit_Job();
}

public static void Submit_Job()
{
    if (Page.User.Identity.IsAuthenticated)
    {
        try
        {
            string username = Context.User.Identity.Name;
        }
        catch
        {
            Context.GetOwinContext().Authentication.SignOut();
        }
    }

    var manager = new UserManager();
    var usernameDatabase = new ApplicationUser() { UserName = username };
    usernameDatabase = manager.Find(username, "password here");
    if (usernameDatabase != null)
    {
        IdentityHelper.SignIn(manager, usernameDatabase, isPersistent: false);  

        string jobTitle = Request.Form["jobTitle"];

        using (var ctx = new CreateUserContext(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString))
        {
            Job job = new Job()
            {
                job_title = jobTitle
            };

            ctx.Jobs.Add(job);
            ctx.SaveChanges();
        }
    }
}

Edit: There are errors for example with Page.User.Identity.IsAuthenticated -- Page, Context, and Request all appear that they cannot be static.

The specific error: (An object reference is required for the non-static field, method, or property 'Control.Page') as well as with Context and Request.

解决方案

Moving it from a simple comment

I had the same issue recently.

Luckily, whenever a user signs in our application, we store the user information encrypted into a session variable, so I retrieve that information, pass it to our user's class constructor, which decrypts it and I can use my logged in users info without a hassle.

So, my solution is to store the users info in the Session, but be careful what you store. Maybe serialize the users object and store in the session, then, whenever you need it

public void Page_Load()
{
    // Retrieve authenticated user information
    UserClass userObject = GetUserCredentials();
    // Call a method that turns the authenticated user object into a string that contains the users session information. Given the sensivity of this information, might want to try to encrypt it or offuscate it. Store it in a session variable as a string
    Session["UserContext"] = userObject.SerializeUser()
    /* rest of the page code goes here */
}

[WebMethod(EnableSession=true)]
public static void CreateJob()
{
    Submit_Job();
}

public static void Submit_Job()
{
    // Lets get the authenticated user information through the session variable. Due to the static nature of the method, we can't access the Session variables directly, so we call it using the current HttpContext
    string serializedUserInfo = )HttpContext.Current.Session["UserContext"].ToString();

   // Let's create the users object. In my case, we have a overcharged constructor that receives the users serialized/encrypted information, descrypts it, deserializes it, and return a instance of the class with the deserialized information
   UserClass userObject = new UserClass(serializedUserInfo);
   // Do whatever the method has to do now!
}

On the subject of serialization, a quick google search with "c# object serialization" will bring you several good matches. XML and JSON are 2 of the most used kind of serialization, specially on web methods. Binary serialization is a good option to also obfuscate information of the logged in user

这篇关于问题WebMethod是静态在C#ASP.NET Codebehind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆