Search code examples
asp.netajaxjquerywebmethod

Using FormsAuthentication on webMethod


I have a page that has a comment section. This section communicates to a WebMethod in order to insert a new comment.

[WebMethod]
public static bool insertComment(string commentString)
{
    //userName validation here
    string userName = (FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name);

    return new CommentClass().InsertComment(commentString, userName);
}

The problem is: "An object reference is required for the non-static field". I know I could send the information from a hidden field, or a div, however, that information field may be changed easily. So which way could be used to know which user is posting, in server side? thanks a lot!


Solution

  • Request object is an instance that lives in Page, so you need a reference to access this object in a static context. You can use HttpContext.Current.Request for accessing the Request in this context.

    [WebMethod]
    public static bool insertComment(string commentString)
    {
        //userName validation here
        string userName = 
               (FormsAuthentication.Decrypt(
                   HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name);
        return new CommentClass().InsertComment(commentString, userName);
    }