由于在单个页面上有多个表单导致的问题,我使用对WebMethod的AJAX调用来提交表单而不是使用ASP控件。但是,在执行此操作时,我用于在数据库中创建新条目的先前方法不再有效,因为WebMethod必须是静态的。
我已经使用ASPX身份验证对我的用户进行了身份验证,并尝试使用代码隐藏检索该用户的用户名和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')以及上下文和请求都需要对象引用。
答案 0 :(得分:0)
将其从简单的评论中移除
我最近遇到了同样的问题。
幸运的是,每当用户登录我们的应用程序时,我们将加密的用户信息存储到会话变量中,因此我检索该信息,将其传递给我们用户的类构造函数,该构造函数对其进行解密,我可以使用我的登录用户信息没有麻烦。
因此,我的解决方案是将用户信息存储在会话中,但要小心存储的内容。也许,序列化用户对象并存储在会话中,然后,无论何时需要它
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!
}
关于序列化的主题,快速谷歌搜索" c#对象序列化"将为您带来几场精彩的比赛。 XML和JSON是最常用的两种序列化,特别是在Web方法上。二进制序列化是一个很好的选项,也可以混淆登录用户的信息