1 視圖類型
- 返回視圖
public ActionResult Index()
{
return View();
}
2 文本類型
可以指定返回的文本內(nèi)容咽瓷,編碼格式和文本類型(MIME類型)
- 返回JavaScript腳本
public ActionResult SetJS()
{
String STR = "alert('ceshi');";
return Content(STR, "text/javascript");
}
- 返回CSS樣式
public ActionResult Css()
{
HttpCookie cookie = Request.Cookies["theme"] ?? new HttpCookie("theme", "default");
switch (cookie.Value)
{
case "Theme1": return Content("body{font-family: SimHei; font-size:1.2em}", "text/css");
case "Theme2": return Content("body{font-family: KaiTi; font-size:1.2em}", "text/css");
default: return Content("body{font-family: SimSong; font-size:1.2em}", "text/css");
}
}
3 JSON類型
public ActionResult Json()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("id", 100);
dic.Add("name", "liming");
return Json(dic, JsonRequestBehavior.AllowGet);
}
注意:若要允許 GET 請求纤泵,請將 JsonRequestBehavior 設(shè)置為 AllowGet。
3 圖片多媒體類型
-圖片類型
public ActionResult Image(string id)
{
string path = Server.MapPath($"/images/{id}.jpg");
return File(path, "image/jpeg");
}
5 JavaScript腳本類型(同文本類型返回腳本的方法)
public ActionResult GetData()
{
string script = "alert('asdf');";
return JavaScript(script);
}
6 文件類型
下載excel表格文件的例子
public FileStreamResult Download()
{
string fileName = "超市設(shè)備臺賬.xlsx";//客戶端保存的文件名
string filePath = Server.MapPath("~/Downloads/123.xlsx");//路徑
LogService.AddOperateLogInfo(CurrentUser.UserID, $"導(dǎo)出設(shè)備臺賬", "導(dǎo)出");//計入操作日志
return File(new FileStream(filePath, FileMode.Open), "text/plain",fileName);
}
7常見程序異常
- 1Json序列化錯誤
image.png
這是因為Json方法實際上采用的是JavaScriptSerializer類的Serialize和Desserialize方法實現(xiàn)的掉丽。JavaScriptSerializer類有一個屬性MaxJsonLength,這個屬性限制了序列化為Json字符串的長度悯搔,默認為4M的Unicode字符串?dāng)?shù)據(jù)佃蚜。若在項目中需要序列大數(shù)據(jù)超過4M,系統(tǒng)就會拋異常了夭咬。可采用如下解決此問題。
在控制器中添加具有返回JsonResult 類型的方法LargeJson(重載加派,一個允許get請求)叫确,然后在需要返回大數(shù)據(jù)json的action調(diào)用,即用return LargeJson()代替原先的return Json()
public JsonResult LargeJson(object data)
{
return new JsonResult()
{
Data = data,
MaxJsonLength = Int32.MaxValue,//Json序列化數(shù)據(jù)限制修改
};
}
public JsonResult LargeJson(object data,JsonRequestBehavior behavior)
{
return new System.Web.Mvc.JsonResult()
{
Data = data,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}