我在ASP.NET中做了第一步,我遇到了类的问题。我想创建一个新的自定义类来支持会话并收集有关我网站上用户数量的信息。 我在文件MySession.cs中创建了一个类,它已被WebMatrix放在名为“App_data”的目录中。 当我尝试在.cshtml文件中使用此类时,它会抛出无法找到该类的信息。 我在Web上发现,该类应该放在App_Code中,所以我已经完成了。但是,在这一刻,它向我显示了一个错误,就是找不到像“请求”这样的类。
如何在WebMatrix中使用自定义类?
来自.cshtml文件的我的c#代码如下:
@{
MySession session = new MySession(60);
session.start();
var db = Database.Open("studia");
var data = db.Query("SELECT COUNT(*) as total FROM sessions");
}
和类文件看起来像:
using System;
using System.Collections.Generic;
using System.Web;
using System.Security.Cryptography;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for sesss
/// </summary>
public class MySession
{
private String _session_id;
private int _session_time;
public MySession(int session_time = 60)
{
_session_time = session_time;
using (MD5 md5Hash = MD5.Create())
{
_session_id = (Request.Cookies["session_id"] != null) ? Server.HtmlEncode(Request.Cookies["sesion_id"].Value) : GetMd5Hash(md5Hash, DateTime.Now);
}
cleanup();
}
public bool isLogged()
{
if (Request.Cookies["session_id"] != null)
{
return true;
}
return false;
}
public void start(string username)
{
DateTime now = DateTime.Now;
var db = Database.Open("studia");
if (isLogged())
{
db.Query("UPDATE sessions SET start_time = " + now + " WHERE session_id = " + _session_id);
}
else
{
db.Query("INSERT INTO sessions (id, start_time, username) VALUES ('" + _session_id + "', '" + now + "', '" + username + "'");
}
HttpCookie session_cookie = new HttpCookie("session_id");
session_cookie.Value = DateTime.Now;
session_cookie.Expires = DateTime.Now.AddSeconds(_session_time);
Response.Cookies.Add(aCookie);
}
public void cleanup()
{
var db = Database.Open("studia");
db.Query("DELETE FROM sessions WHERE start_time < " + (DateTime.Now - _session_time));
}
static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
}
答案 0 :(得分:1)
如果要在类中引用Request对象(而不是在页面文件中),则需要使用HttpContext.Current,例如
public bool isLogged()
{
return HttpContext.Current.Request.Cookies["session_id"] != null;
}