Series directory
Action Overview
At the end of the previous article, we performed the "door" of the action call ":
If (! Actioninvoker. invokeaction (controllercontext, actionname ))
It is helpful to have a general understanding before you thoroughly study the details of the call process. The invokeaction method follows the following sequence:
Find action:The Action Search Method in MVC seems to be a bit complicated. It involves an actiondescriptor, but in principle it is reflected. In the futureArticle.
Verification and filtering:Well-knownIactionfilterAndIauthorizationfilterThis part takes effect. Before they actually execute the actionIresultfilterOrIexceptionfilterSuch a filter is executed after the action is executed, which is not shown in the figure.
Execute action:Real User AccessCodeExecution, through reflection call, complicated parameter provision and binding are also involved before the call, which will be involved in future articles.
Execution result: actionresultThis plays a key role,ActionresultThere are multiple derivatives, the most common of which is viewresult. Actionresult is the final "Fruit" of the previous step.ExecuteresultAbstract method. An httprespose is correctly constructed and is ready to be sent back to the client.
Starting with actionresult
As mentioned in the previous article, we canControllerOfExecuteYou can directly operate httpcontext. Response in the method to bypass action. Even if you are using action, you can still directly operate response in the action as follows:
Public class simplecontroller: controller {public void myactionmethod () {response. write ("I'll never stop using the <blink> blink </blink> tag ");//... or... response. redirect ("/Some/other/url ");//... or... response. transmitfile (@ "C: \ files \ somefile.zip ");}}
However, this method is difficult to maintain and unit test is difficult. Therefore, the MVC Framework recommends that action returnActionresultAnd called by the FrameworkActionresultOfExecuteresultMethod, similar toCommand mode. You will see that the use of this design model is very incisive here.
Actionresult is a full abstract class that can no longer be abstracted. It defines a uniqueExecuteresultMethod, the parameter isControllercontext, Which encapsulates many objects including httpcontext and is the only context information for rewriting this method:
Namespace system. Web. MVC {public abstract class actionresult {public abstract void executeresult (controllercontext context );}}
MVC has a lot of built-in practicalActionresultSuch:
Let's look at a simple implementation class.RedirectresultHow to ImplementExecuteresult. Here I found a cause of an exception that I have encountered: Child actions are not allowed to perform redirect actions, meaning that redirection is not allowed in subactions.
Public override void executeresult (controllercontext context) {If (context = NULL) {Throw new argumentnullexception ("context");} If (context. ischildaction) {Throw new invalidoperationexception (mvcresources. redirectaction_cannotredirectinchildaction);} string destinationurl = urlhelper. generatecontenturl (URL, context. httpcontext); context. controller. tempdata. keep (); context. httpcontext. response. redirect (destinationurl, false/* endresponse */);}
In this Code, the implementation of executeresult is much simpler.ViewresultImplementation is much more complicated.ViewresultWill be involved in the view.
There are manyAuxiliary MethodsThe required actionresult is returned in the action, which is listed below:
Content (): returns contentresult
This actionresult is rarely used, because its basic usage is to return text. The following code may persuade you
Public contentresult rssfeed () {story [] stories = getallstories (); // fetch them from the database or wherever // build the RSS feed document string encoding = response. contentencoding. webname; xdocument RSS = new xdocument (New xdeclaration ("1.0", encoding, "yes"), new xelement ("RSS", new xattribute ("version ", "2.0"), new xelement ("channel", new xelement ("title", "example RSS 2.0 feed"), from story in stories select new xelement ("item ", new xelement ("title", story. title), new xelement ("Description", story. description), new xelement ("Link", story. URL); Return content (RSS. tostring (), "application/RSS + XML") ;}
The above code returns an RSS feed. It is worth noting that the second parameter of content is a contenttype (MIME type, see www.iana.org/assignments/media-types). If this parameter is not specified, the contenttype of text/html is used.
In fact, our action can return a non-actionresult. Before executing the return result of the action, MVC will ensure that the return value is converted into an actionresult, one step in the process, it is to convert the results of non-null and non-actionresult into strings and wrap them into contentresult:
Protected virtual actionresult createactionresult (controllercontext, actiondescriptor, object actionreturnvalue) {If (response = NULL) {return New emptyresult ();} actionresult = (response as actionresult )?? New contentresult {content = convert. tostring (actionreturnvalue, cultureinfo. invariantculture)}; return actionresult ;}
JSON (): Return jsonresult
The Controller JSON method can return a jsonresult,For security reasons, jsonresult only supports post., Set response. contenttype = "application/JSON"; and UseJavascriptserializerSerialize the object and return it to the client. Use jsonresult as follows:
Class citydata {Public String city; Public int temperature;} [httppost] public jsonresult weatherdata () {var citiesarray = new [] {New citydata {city = "London ", temperature = 68}, new citydata {city = "Hong Kong", temperature = 84 }}; return JSON (citiesarray );}
JavaScript (): returns javascriptresult
The JavaScript method instantiates a javascriptresult. javascriptresult is just a simple setting of response. contenttype = "application/X-JavaScript ";
File (): returns binary data or files.
Fileresult is an abstract class. Multiple loads of the file method return different fileresult:
Filepathresult: Directly send a file to the client
Public filepathresult downloadreport () {string filename = @ "C: \ files \ somefileworkflow"; return file (filename, "application/pdf", "annualreport.pdf ");}
Filecontentresult: Byte bytes are returned to the client.
Public filecontentresult getimage (INT productid) {var Product = productsrepository. products. first (x => X. productid = productid); Return file (product. imagedata, product. imagemimetype );}
Filestreamresult: Returned stream
Public filestreamresult proxyexampledotcom () {WebClient WC = new WebClient (); stream = WC. openread ("http://www.example.com/"); Return file (stream, "text/html ");}
Partialview () and view (): Return partialviewresult and viewresult respectively.
Partialviewresult and viewresult are very complex and will be discussed in detail later.
Redirect (): returns redirectresult
The redirection result is generated. The preceding figure shows the implementation of redirectresult.
Redirecttoaction (), redirecttoroute (): returns redirecttorouteresult
Redirecttorouteresult is also a jump result, but it has the "route table traversal Capability", that is, it has the characteristics of URL outbound. For more information, see ASP. net mvc (3)
For more details about the derived class of actionresult, see the MVC source code file.
Labor fruit, reproduced please indicate the source: http://www.cnblogs.com/P_Chou/archive/2010/11/26/details-asp-net-mvc-06.html