Issue with WebMethod being Static in C# ASP.NET Co

2019-07-15 05:41发布

问题:

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.

回答1:

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