.NET MVC5简介(三)Result
程序员文章站
2022-05-29 10:33:43
Ajax请求数据响应格式,一个醒目组必须是同意的,前端才知道怎么应付,还有很多其他情况,比如异常了,有ExceptionFilter,按照固定格式返回,比如没有权限,Authorization,按照固定格式返回。 Http请求的本质: 请求--应答式,响应可以那么丰富?不同的类型其实方式一样的,只不 ......
ajax请求数据响应格式,一个醒目组必须是同意的,前端才知道怎么应付,还有很多其他情况,比如异常了,有exceptionfilter,按照固定格式返回,比如没有权限,authorization,按照固定格式返回。
http请求的本质:
请求--应答式,响应可以那么丰富?不同的类型其实方式一样的,只不过有个contenettype的差别,html--text/html、json--application/json、xml/application/xml、js--application/javascript、ico--image/x-icon、image/gif、image/jepg、image/png.....
这个等于是http协议约定,web框架和浏览器共同支持的。其实就是服务器告诉浏览器如何处理这个数据,从页面下载pdf或者页面展示pdf靠的就是contenttype,application/pdf、application/octet-stream。
mvc各种result的事,jsonresult实际上就是jsonresult,继承actionresult,然后重写executeresult方法,指定contenttype为application/json,然后将data序列化成字符串写入stream,我们可以随意扩展,只需要把数据放到response,指定好contenttype
contenttype对照表:
/// <summary> /// 返回actionresult--mvc框架会执行其executeresult方法--- /// </summary> /// <returns></returns> public jsonresult jsonresultin() { return json(new ajaxresult() { result = doresult.success, debugmessage = "这里是jsonresult" }, jsonrequestbehavior.allowget); }
比如我们现在来扩展个newtonjsonresult
public class newtonjsonresult : actionresult { private object data = null; public newtonjsonresult(object data) { this.data = data; } public override void executeresult(controllercontext context) { httpresponsebase response = context.httpcontext.response; response.contenttype = "application/json"; response.write(newtonsoft.json.jsonconvert.serializeobject(this.data)); } }
调用的时候:
/// <summary> /// 返回actionresult--mvc框架会执行其executeresult方法--- /// </summary> /// <returns></returns> public newtonjsonresult jsonresultnewton() { return new newtonjsonresult(new ajaxresult() { result = doresult.success, debugmessage = "这里是jsonresult" }); }
ajaxresult:
public class ajaxresult { public ajaxresult() { } public string debugmessage { get; set; } public string promptmsg { get; set; } public doresult result { get; set; } public object retvalue { get; set; } public object tag { get; set; } } public enum doresult { failed = 0, success = 1, overtime = 2, noauthorization = 3, other = 255 }
自定义扩展xmlresult
/// <summary> /// 自定义扩展xml格式result /// </summary> public class xmlresult : actionresult { private object _data; public xmlresult(object data) { _data = data; } public override void executeresult(controllercontext context) { var serializer = new xmlserializer(_data.gettype()); var response = context.httpcontext.response; response.contenttype = "text/xml"; serializer.serialize(response.output, _data); } }
public xmlresult xmlresult() { return new xmlresult(new ajaxresult() { result = doresult.success, debugmessage = "这里是jsonresult" }); }
现在,我们不写返回值,直接写入stream
/// </summary> public void jsonresultvoid() { httpresponsebase response = base.httpcontext.response; response.contenttype = "application/json"; response.write( newtonsoft.json.jsonconvert.serializeobject(new ajaxresult() { result = doresult.success, debugmessage = "这里是jsonresult" })); }