zoukankan      html  css  js  c++  java
  • MVC Controller return 格式之JsonResult、ContentResult、RedirectResult……

     
    //语法

    public
    class JsonResult : ActionResult public class ContentResult : ActionResult public class RedirectResult : ActionResult eg: public ActionResult Index() {   return View(); } //返回一个子页 public ActionResult Ascx() {   return PartialView(); } //返回文本 public ActionResult Text() {   return Content("这是一段文本"); } 返回Json public JsonResult GetJson() { var Data = new { demo = demoList, Total = demoList.Count}; //在这里必须要设置JSON的请求行为为GET return Json(Data, JsonRequestBehavior.AllowGet); } public ContentResult DoSelect(string StudentId) {   var result = "success";   return Content(JsonConvert.SerializeObject(result, Formatting.None)); } public ActionResult Index() { //这个是BiewBag传值的方法 ViewBag.Title = "Demo一览画面"; if (0 == demoList.Count) { //模拟select * from DemoModels for (int i = 1; i <= 7; i++) { demoList.Add(this.CreateDemoModels(i)); } } return View(demoList); } //输出JS文件 public ActionResult Js() {   return JavaScript("var x=0;"); } //页面跳转 1.跳转到Url public RedirectResult rdurl() {   return Redirect("http://www.baidu.com"); } 2.跳转到Action public ActionResult rdaction() { return RedirectToAction("Index","Eice"); } 3.跳转到Routing规则 public ActionResult rdrouting() {   return RedirectToRoute("Default",//Route名   new{Controller = "Eice",Action = "Index" }); } //显示文件 public ActionResult fn() {   return File("/Content/site.css","text/css"); }
    
    
            //Excel导入模板下载
            public FileResult GetFile()
            {
                const string url = "~/TempExcel/商品评论模板.xls";
                var fileName = Server.MapPath(url);
                var name = Path.GetFileName(fileName);
                return File(fileName, "application/ms-excel", Url.Encode(name));
            }

     另外,

    Webapi的接口返回值主要有四种类型

    • void无返回值
    • IHttpActionResult
    • HttpResponseMessage
    • 自定义类型   

    详情参见:http://www.cnblogs.com/zfdcp-028/p/5788649.html

    跳转到同一控制器内的action和不同控制器内的action、带有参数的action跳转和不带参数的action跳转。

    一、RedirectToAction("Index");//一个参数时在本Controller下,不传入参数。

    二、RedirectToAction(ActionName,ControllerName) //可以直接跳到别的Controller.

    三、RedirectToRoute(new {controller="Home",action="Index"});//可跳到其他controller

    四、RedirectToRoute(new {controller="Home",action="Index", id=param});//可跳到其他controller,带参数。

    五、Response.Redirect("Index?id=1");//适用于本controller下的方法名称,可带参数。
    六、return Redirect("Index");//适用于本controller下的方法名称。

    七、return View("Index"); //直接显示对应的页面 不经过执行Controller的方法。 
    八、return View("~/Views/Home/Index.aspx");//这种方法是写全路径,直接显示页面,不经过Controller方法
    九、return View();//直接显示页面,不经过Controller方法

    重写返回结果HttpResponseMessage

        public class BaseController : ApiController
        {
            public int loginid { get; set; }
    
            public string loginname { get; set; }
    
    
            public BaseBll baseBll { get; set; }
    
    
            protected override void Initialize(HttpControllerContext controllerContext)
            {
                //初始化请求上下文
                base.Initialize(controllerContext);
                try
                {
                    new SortedDictionary<string, string>();
                    string username = string.Empty;
                    HttpRequestHeaders headers = controllerContext.Request.Headers;
                    if (headers.Contains("e"))
                    {
                        text = (headers.GetValues("e").FirstOrDefault<string>().ToString() ?? string.Empty);
                        text = System.Web.HttpUtility.UrlDecode(username);
                    }
                    UserInfoEntity userInfo = new LoginBll().GetUserInfo(username);
                    this.loginid = userInfo.LoginID;
                    this.loginname = userInfo.LoginName;
                    List<UserAuthorityEntity> tempList = userInfo.UserRole.UserAuthority;
                    //不存在安全问题 后续文章有权限验证
                    if (tempList.Where(c => c.AuthorityName == "权限名称").ToList().Count > 0)
                    {   
                        //调用一个有权限的bll层
                        this.baseBll = new SeniorBll();
                    }
                    else
                    { 
                        //调用一个没有权限的bll层
                        this.baseBll = new OrdinaryBll();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("Initialize", ex);
                }
            }
            /// <summary>
            /// 设置action返回信息
            /// </summary>
            /// <param name="result">返回实体</param>
            /// <returns></returns>
            protected HttpResponseMessage GetHttpResponseMessage(object result)
            {
                BaseResponseEntity<object> responseBaseEntity = new BaseResponseEntity<object>(0, result, string.Empty);
                return new HttpResponseMessage()
                {
                    Content =
                       new StringContent(JsonConvert.SerializeObject(responseBaseEntity, dtConverter), System.Text.Encoding.UTF8,
                           "application/json")
                };
            }
            /// <summary>
            /// 设置action返回信息
            /// </summary>
            /// <param name="result">返回实体</param>
            /// <param name="msg">返回的信息参数</param>
            /// <returns></returns>
            protected HttpResponseMessage GetHttpResponseMessage(object result, ref string msg)
            {
                BaseResponseEntity<object> responseBaseEntity = new BaseResponseEntity<object>(0, result, msg ?? string.Empty);
                return new HttpResponseMessage()
                {
                    Content =
                       new StringContent(JsonConvert.SerializeObject(responseBaseEntity, dtConverter), System.Text.Encoding.UTF8,
                           "application/json")
                };
            }
        }

    参考:http://blog.csdn.net/l1158513573/article/details/77045213   WebApi开发爬坑记之·一重写ApiController

  • 相关阅读:
    GSON -JSON 反序列化-多节点名称支持
    Jedis 分片原理
    闭锁-CountDownLatch
    XML序列化及反序列化
    用GIT操作SVN
    报表worker-CPU使用率过高原因排查
    二.PlantUML 之活动图
    一.PlantUML 与 IDEA 集成
    ArrayList
    VI常用命令
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/5206019.html
Copyright © 2011-2022 走看看