.NET MVC学习笔记一
1、延迟请求验证机制:在“web.config”里配置<httpRuntime requestValidationMode=”4.5” />
2、启用自定义错误:在“web.config”里配置
<system.web>
<customErrorsmode="On"defaultRedirect="http://www.jjyc.org">
<errorstatusCode="404"redirect="~/error/notfound"></error>
</customErrors>
</system.web>
3、.NET MVC操作MySQL数据库
3.1 先去MySQL官网下载mysql-connector-net,将下载好的dll文件引入到工程中。
3.2 在项目中,引入using MySql.Data.MySqlClient;
3.3参考代码:
MySqlConnection myConnection = null;
MySqlCommand myCommand = null;
MySqlDataReader myDataReader = null;
//连接字符串拼装
myConnection= newMySqlConnection("Host = localhost;Database = 数据库;Username = 用户名;Password =密码");
//连接
myConnection.Open();
if(myConnection.State.ToString()=="Open")
{
连接MYSQL成功!;
}
//数据库操作
myCommand= newMySqlCommand("select * from test",myConnection);
myDataReader= mycom.ExecuteReader();
//一次次读,读不到就结束
while (myDataReader.Read())
{
读取字段信息;
}
//////关闭相关对象
myDataReader.Close();
myConnection.Close();
4、web.config配置数据库连接方法一
4.1 web.config文件:加在<appsettings>和</appsettings> 之间
<appsettings>
<add
key="connstring" value="uid=xx;pwd=xx;database=batabase_name;server=(local)"/></appsettings>
4.2 取连接字符串:
string myvar=configurationsettings.appsettings["connstring"];
5、web.config配置数据库连接方法二
5.1 web.config文件:加在</configSections>后面
<connectionStrings>
<add name="SqlConnStr" connectionString="user id=xx;password=xx;initial catalog=database_name;data source=.\sqlxxxx"/>
</connectionStrings>
5.2 取连接字符串
string connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SqlConnStr"].ConnectionString;
或
protectedstaticstring connectionString = ConfigurationManager.ConnectionStrings["SqlConnStr"].ConnectionString;
6、一个完整的.net 操作mysql数据
6.1 数据新增
publicclassUserInfoEntity
{
publicstaticstring connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
publicstring UserName { get; set; }
publicstring UserPassword { get; set; }
publicbool Add()
{
///////////////////获取MYSQ看数据返回值////////////////////////////
MySqlConnection myconn = null;
MySqlCommand mycom = null;
//连接字符串拼装
myconn = newMySqlConnection(connectionString);
//连接
myconn.Open();
mycom = newMySqlCommand("insert into testuser (username,userpassword) values(?userName,?userPassword)", myconn);
mycom.Parameters.Add("@userName", MySqlDbType.VarChar, 32).Value = UserName;
mycom.Parameters.Add("@userPassword", MySqlDbType.VarChar, 32).Value = UserPassword;
int rows = mycom.ExecuteNonQuery();
//////关闭相关对象
if (myconn!= null) { myconn.Close(); }
returntrue;
}
6.2 数据查询
注意:DbConnection是一个静态的连接类,需要自己写。或者这块直接用连接字符串替代。
//连接字符串拼装
MySqlConnection myconn = new MySqlConnection(DbConnection.connectionString);
MySqlCommand mycom = new MySqlCommand();
mycom.CommandText = "select * from testuser where username=?userName and userpassword=?userPassword";
mycom.Parameters.Add("@userName", MySqlDbType.VarChar, 32).Value = UserName;
mycom.Parameters.Add("@userPassword", MySqlDbType.VarChar, 32).Value = UserPassword;
mycom.Connection = myconn;
myconn.Open();
var rows = mycom.ExecuteScalar();
mycom.Connection.Close();
7、.NET MVC自己编写登录验证(常规版)
7.1 要先引入using System.Web.Security;
7.2 验证值写入cookie:
FormsAuthenticationTicket authTicket = newFormsAuthenticationTicket(
1,
"名称",
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
"用户数据"
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = newHttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
如果要记住登录认证(上文中设置的记住时间是30分钟):
authTicket中的 false,改为true。
authCookie.Expires = ticket.encryptedTicket;
7.3 认证的cookie值获取:
if (User.Identity.IsAuthenticated)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string userinfo = authTicket.UserData;
string userinfoName = authTicket.Name;
}
8、.NET MVC自己编写登录验证(简洁版)
public ActionResult LoginIn(string username, string password)
{
string userdata = username + "|" + password;
FormsAuthentication.SetAuthCookie(userdata,true);
return RedirectToAction("Index");
}
判断是否登录,取cookie里的登录信息。
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
string userinfo = User.Identity.Name;
}
return View();
}
9、用户注销登录认证信息
FormsAuthentication.SignOut();
10、在MVC中使用注解方式的认证[Authorize(Roles = "admin")]
10.1 将FormsAuthenticationTicket authTicket中用户数据中填写:admin。见本章内容 7.2条。
10.2 在Global.asax中添加验证
///<summary>
///构造方法
///</summary>
public MvcApplication()
{
AuthorizeRequest += newEventHandler(Application_AuthenticateRequest);
}
protectedvoid Application_AuthenticateRequest(Object sender,EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(newchar[] { ',' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity,roles);
}
}
11、.net mvc 引入部分视图
11.1 Razor 语法:
@Html.Partial
@{Html.RenderPartial();}
@{Html.RenderAction();}
@RenderPage()
11.2 用法:
一般用@{Html.RenderPartial();},如果引入的页面需要使用model同数据库交互,就用@{Html.RenderAction();}
12、使用MD5加密
string A; //加密前数据
string B; //加密后数据
B=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(A,"MD5")
13、利用JSON实现省市菜单联动
13.1 创建省MODEL
public class Province
{
public int ID { get; set; }
public string Name { get; set; }
}
public class City
{
public int ID { get; set; }
public int ProvinceID { get; set; }
public string Name { get; set; }
public string ZipCode { get; set; }
}
13.2 创建基础省市数据
public static class ProvincAndCityBaseData
{
public static List<Province> GetProvices()
{
List<Province> result = new List<Province>();
result.Add(new Province(){ ID = 1, Name = "河北省"});
result.Add(new Province(){ ID = 2, Name = "江苏省"});
result.Add(new Province(){ ID = 3, Name = "上海市" });
return result;
}
public static List<City> GetCitiesByProvince(int provinceId)
{
List<City> result = new List<City>();
result.Add(new City() { ID = 1, Name = "石家庄市",ProvinceID = 1,ZipCode = "001"});
result.Add(new City() { ID = 2, Name = "张家口市", ProvinceID = 1, ZipCode = "002"});
result.Add(new City() { ID = 3, Name = "邯郸市", ProvinceID = 1, ZipCode = "003" });
result.Add(new City() { ID = 4, Name = "南京市", ProvinceID = 2, ZipCode = "004" });
result.Add(new City() { ID = 5, Name = "苏州市", ProvinceID = 2, ZipCode = "005" });
result.Add(new City() { ID = 6, Name = "常州市", ProvinceID = 2, ZipCode = "006" });
result.Add(new City() { ID = 7, Name = "静安区", ProvinceID = 3, ZipCode = "007" });
result.Add(new City() { ID = 8, Name = "杨浦区", ProvinceID = 3, ZipCode = "008" });
return result.Where(r => r.ProvinceID == provinceId).ToList();
} }
13.3 编写控制层
public JsonResult GetProvinces()
{
List<SelectListItem> items = new List<SelectListItem>();
var provinces = ProvincAndCityBaseData.GetProvices();
foreach (Province p in provinces)
{
items.Add(new SelectListItem()
{
Text = p.Name,
Value = Convert.ToString(p.ID)
});
}
if (!items.Count.Equals(0))
{
items.Insert(0, new SelectListItem(){Text = "请选择",Value = ""});
}
return Json(items, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCities(string id)
{
List<SelectListItem> items = new List<SelectListItem>();
if (!string.IsNullOrEmpty(id))
{
var cities = ProvincAndCityBaseData.GetCitiesByProvince(int.Parse(id));
foreach (City c in cities)
{
items.Add(new SelectListItem()
{
Text = string.Concat(c.ZipCode, " ",c.Name),
Value = c.ID.ToString()
});
}
if (!items.Count.Equals(0))
{
items.Insert(0, new SelectListItem(){Text = "请选择",Value = ""});
}
}
return Json(items, JsonRequestBehavior.AllowGet);
}
13.4 编写视图
选择省:<select id="p"></select> <br/>
选择市:<select id="c"></select>
@section scripts {
<script type="text/javascript">
$(function() {
getProvince();
$('#p').change(function() {
changeCity();
});
});
//加载省
function getProvince() {
$.getJSON('@Url.Action("GetProvinces","Home")', function (data) {
$('#p').empty();
$.each(data, function(i, item) {
$('#p').append($('<option></option>').val(item.Value).text(item.Text));
});
});
}
//设置城市清空
function emptyCity() {
$('#c').empty();
$('#c').append($('<option></option>').val('').text('请选择'));
}
//根据省加载城市
function changeCity() {
var selectedProvinceId = $.trim($('#p option:selected').val());
if (selectedProvinceId.length == 0) {
emptyCity();
} else {
$.getJSON('@Url.Action("GetCities","Home")', { id: selectedProvinceId }, function (data) {
$('#c').empty();
$.each(data, function(i, item) {
$('#c').append($('<option></option>').val(item.Value).text(item.Text));
});
});
}
} </script>
}