Objective
Today we come to achieve a special demand, this demand is not too much, but a bit against the real purpose of WEBAPI, Webapi is only as a transmission of data, but not in the development of the project can not be expected to implement a page to display the list in real time and other actions. Now let's take a look.
Topic Introduction
When we build an application, we can choose whether to build the WEBAPI project, we choose to build the Webapi, and at the same time create an index HTML page in its root directory, so it looks like this:
Let's run to see if the results are displayed correctly:
From here we can see that there seems to be no problem we need to explain this section, the introduction here is only for us to play, the actual development will be completely webapi out as a service to carry out data transmission, and here to correctly access to the index page is still dominated by MVC, Webapi Homestay is webhost, so accessing the content under its directory will undoubtedly be accessed if we isolate the WEBAPI completely, which is not dependent on IIS and is implemented using Slef-host. (Refer to the previous series for webhost and Self-host in Webapi).
Completely pumped away from Webapi
Let's build a Windows application named Webapireturnhtml.
We've created a new Httpserverhost class that uses Httpselfhostserver to listen for HTTP requests with the following code:
Public classHttpserverhost {/// <summary> ///Httpselfhostserver Instances/// </summary> PrivateHttpselfhostserver _server; /// <summary> ///start the HTTP server/// </summary> Public voidStart () {varConfig =NewHttpselfhostconfiguration ("http://localhost:8080"); Config. MaxReceivedMessageSize=int. MaxValue; Config. Routes.maphttproute ("Default","Api/{controller}/{action}"); //To set the maximum receive message sizeConfig. MaxReceivedMessageSize =int. MaxValue; Config. Formatters.clear (); Config. Formatters.add (NewJsonpformatter ()); _server=Newhttpselfhostserver (config); //allow cross-domain_server. CONFIGURATION.MESSAGEHANDLERS.ADD (NewCorshandler ()); _server. OpenAsync (). Wait (); } }
Let's demonstrate the effect:
The result is an error, and we should be aware that you should run vs as an administrator.
We immediately add the following test classes:
Public class Homecontroller:apicontroller { [httpget] publicstring Test () { return" OK"; } }
Let's look at the results of the demo:
The whole process of completely pulling out of the WEBAPI is so simple, then we go back to the beginning of the topic introduction, we set up the index page under this project as a visit to try:
The results are as follows:
At this point we are disappointed, completely out of the WEBAPI at this time to access the static resources, at this time we use the Read file string form to return the static resource, as follows:
Publichttpresponsemessage gethtml () {varCurrentRunPath =AppDomain.CurrentDomain.BaseDirectory; varSubstringbin = Currentrunpath.indexof ("bin"); varPath = Currentrunpath.substring (0, Substringbin) +"index.html"; varHttpresponsemessage =NewHttpresponsemessage (); Httpresponsemessage.content=Newstringcontent (File.readalltext (path), Encoding.UTF8); HttpResponseMessage.Content.Headers.ContentType=NewMediatypeheadervalue ("text/html"); returnHttpresponsemessage; }
Let's take a look at the results:
As requested above, we can set the routing characteristics as follows:
[HttpGet] [Route ("Index")]
The access path becomes localhost:8080/index is more concise. In order to achieve such a demand can only fair bet, if it is loading pictures, what should be? Of course there is a solution to the above since there is read string stringcontent, that certainly has to read the picture stream, will the above
Newnew mediatypeheadervalue ("text/html");
You can modify the following:
New Streamcontent (new FileStream (Path, FileMode.Open)); New Mediatypeheadervalue ("image/*");
So now the question, how to request JS in the above index.html page? Now that we have this idea, it's good to do it, and we'll keep looking down.
The return JS definition in the controller is as follows:
[HttpGet] PublicHttpresponsemessage Getjs (stringfile) { varCurrentRunPath =AppDomain.CurrentDomain.BaseDirectory; varSubstringbin = Currentrunpath.indexof ("bin"); varPath = Currentrunpath.substring (0, Substringbin) +file; varHttpresponsemessage =NewHttpresponsemessage (); Httpresponsemessage.content=Newstringcontent (File.readalltext (path), Encoding.UTF8); HttpResponseMessage.Content.Headers.ContentType=NewMediatypeheadervalue ("Text/javascript"); returnHttpresponsemessage; }
To create a index.js in the root directory, define the function as follows:
function Btnclick () { alert ("Call Index.js succeeded");}
Request Index.js, and the structure is as follows:
Let's go back to the demo:
By the end of this, we have reached our needs.
Summarize
There is a little bit of confusion here, if you need to start config in WebAPi2 . Maphttpattributeroutes (); If we add [Route index] when we request the index method above, we need to make the following changes when requesting Index.js
<script type= "Text/javascript" src= "getjs?file=/index.js" ></script><script type= "text/ JavaScript "src=" Api/home/getjs?file=/index.js "></script>
However, there should be no config in the WebAPi2.2 . Maphttpattributeroutes (); It is assumed that the route attribute has been started by default but at this point in the above request the index method when the routing qualitative [route ("Index")] at this time the index method is not requested at all, I do not know what the reason!
Special requirements have a special method of implementation, if there is no such demand for the proposed to achieve this, at the same time do not think more will be stagnant feeling this is impossible, but not impossible, right? It may be said that it is not too desirable to store the page in Webapi, if it can be placed in other UI, I have to do so, the need for this, only to do so, of course, you can also directly put the style and script on the server through the CDN to load, only to display a list so that a few other actions, There is no need for such a big gesture.
The special need to completely pull away from Webapi returns HTML, CSS, JS, Image