//语法
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 ( == demoList.Count) { //模拟select * from DemoModels
for (int i = ; i <= ; i++)
{ demoList.Add(this.CreateDemoModels(i)); }
}
return View(demoList);
} //输出JS文件
public ActionResult Js()
{
  return JavaScript("var x=0;");
} //页面跳转
.跳转到Url public RedirectResult rdurl()
{
  return Redirect("http://www.baidu.com");
}
.跳转到Action public ActionResult rdaction()
{
return RedirectToAction("Index","Eice");
} .跳转到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 > )
{
//调用一个有权限的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>(, 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>(, 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

MVC Controller return 格式之JsonResult、ContentResult、RedirectResult……的更多相关文章

  1. MVC Controller return 格式

    所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件.而它的返回类型是ActionResult如 public ActionResult Index()  ...

  2. MVC Controller return 格式分类及用法

    概述 所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件.而它的返回类型是ActionResult如 public ActionResult Index ...

  3. mvc Controller类介绍

    1.Controller类 i.Controller必须为公开类: ii.必须以Controller结尾: iii.继承Controller基类或实现IController接口的类: iv.类中必须包 ...

  4. 一步步学习ASP.NET MVC3 (8)——EmptyResult,ContentResult,RedirectResult

    请注明转载地址:http://www.cnblogs.com/arhat 上一章,我们阐述了Controller,Action和ActionResult所代表的含义及使用,本章继续研究ActionRe ...

  5. System.Web.Mvc.Controller.cs

    ylbtech-System.Web.Mvc.Controller.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicK ...

  6. .NET/ASP.NET MVC Controller 控制器(IController控制器的创建过程)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC IControllerFactory 控制器工厂接口 3.ASP.NETMVC DefaultControllerFactory 默认控制器工厂 4 ...

  7. MVC Controller Dependency Injection for Beginners【翻译】

    在codeproject看到一篇文章,群里的一个朋友要帮忙我翻译一下顺便贴出来,这篇文章适合新手,也算是对MEF的一个简单用法的介绍. Introduction In a simple stateme ...

  8. 转:【Spring MVC Controller单例陷阱】

    http://lavasoft.blog.51cto.com/62575/1394669/ Spring MVC Controller默认是单例的: 单例的原因有二:1.为了性能.2.不需要多例. 1 ...

  9. MVC Controller 链接到 API Controller 以及反向链接

    MVC Controller 链接到 API Controller 以及反向链接 问题 想创建一个从 ASP.NET MVC controller 到 ASP.NET Web API controll ...

随机推荐

  1. ZOJ 3332 Strange Country II (竞赛图构造哈密顿通路)

    链接:http://www.icpc.moe/onlinejudge/showProblem.do?problemCode=3332 本文链接:http://www.cnblogs.com/Ash-l ...

  2. 对三个数排序 Exercise06_05

    import java.util.Scanner; /** * @author 冰樱梦 * 时间:2018年下半年 * 题目:对三个数排序 * */ public class Exercise06_0 ...

  3. a + b ——C语言初学者百题大战之四

    #include <stdio.h> int main() { int a,b; scanf("%d %d",&a,&b); printf(" ...

  4. 13南理工test01:进制转化

    #include<iostream> #include<cstdlib> using namespace std; int main() { //cout<<5/2 ...

  5. NSOperation的并发与非并发

    NSoperation也是多线程的一种,NSopertaion有2种形式  (1) 并发执行       并发执行你需要重载如下4个方法     //执行任务主函数,线程运行的入口函数    - (v ...

  6. C# 6.0可能会支持模式匹配了

    今天在CodePlex的Roslyn讨论区发现了一个帖子:Draft spec for records and pattern-matching in C#,估计MS计划在C# 6.0中支持模式匹配了 ...

  7. Delphi 通过SQLite3, SQLiteTable3 操作数据库

    var sql, sFile:string; db:TSQLiteDatabase;begin try sFile := G_AppPath + CH_IPC712Db; //if FileExist ...

  8. JS 创建长度为100的数组,数值为角标

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. 计算两个经纬度之间的距离(python算法)

    EARTH_REDIUS = 6378.137 def rad(d): return d * pi / 180.0 def getDistance(lat1, lng1, lat2, lng2): r ...

  10. python抓取日本网站上iphone5的价格

    抓取日本网站上iphone5的价格,比国内便宜好多汇率换算是在中国银行的网站上取得 #-*- coding:utf-8 -*- import requests import time from bs4 ...