1

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.

5
  • Where specifically are things breaking and what's the error message? Commented Jan 18, 2017 at 20:57
  • @arbitrarystringofletters sorry I just added the error message with some more information Commented Jan 18, 2017 at 21:03
  • I had the same issue recently. Luckily, whenever a user signs in out 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 users logged in 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, deserialize it Commented Jan 18, 2017 at 21:05
  • This question might help out. Try adding <modules runAllManagedModulesForAllRequests="true" /> to your config file. Commented Jan 18, 2017 at 21:10
  • @CJLopez I never thought of that thank you! Is there anywhere you can link to that may show how to do this? I've haven't used session variables before. Commented Jan 18, 2017 at 21:16

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! This is exactly what I needed. I really appreciate your help
Glad to hear it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.