Integration of ASP and Office Web apps

Source: Internet
Author: User
Tags urlencode hosting

In fact, there are articles about the integration of Office Web Apps online, and it's typical how to integrate Office Web apps into your own system (a) and how to integrate Office Web apps into your own system (ii), and Microsoft's website has a demo.

Here's a brief description of the principle: the Office Web Apps (owas) player, a customer service, will visit the files of our ASP. NET site and present it. The APIs we use most often have the following 3, for example:

GET Api/wopi/files/{name}?access_token={access_token}
GET api/wopi/files/{name}/contents?

Access_token={access_token}
POST Api/wopi/files/{name}/contents?access_token={access_token}

As for each API to do something here is not much to say. The first one is Owas check the file, the message is the JSON data format, the second is Owas get the file stream, and the third is the Owas post file stream (save the change file). Let's take a look at the implementation of the first API:

[Route ("files/{name}/")]        Public Checkfileinfo GetFileInfo (string name, String access_token)        {            Validate (name, access_token);            var fileInfo = _filehelper.getfileinfo (name);            BOOL updateenabled = false;            if (bool. TryParse (webconfigurationmanager.appsettings["updateenabled"). ToString (), out updateenabled))            {                fileinfo.supportsupdate = updateenabled;                Fileinfo.usercanwrite = updateenabled;                Fileinfo.supportslocks = updateenabled;            }            return fileInfo;        }
Here'sThe Validate (name, Access_token) method is primarily to verify that the requested file name is the same as the parameter access_token . The main is to verify whether it is an illegal interview. Returns a Checkfileinfo object. The definition of Checkfileinfo is as follows:

public class Checkfileinfo    {public        checkfileinfo ()        } {this            . Supportsupdate = false;            This. Usercanwrite = false;        }        public string Basefilename {get; set;}        public string ownerID {get; set;}        Public long Size {get, set;}//in bytes Public        string SHA256 {get; set;}//sha256:a-bit sha-2-encoded [FIPS18 0-2] Hash of the file contents public        string Version {get; set;}  Changes when file changes.        public bool Supportsupdate {get; set;}        public bool Usercanwrite {get; set;}        public bool Supportslocks {get; set;}    }

Now let's take a look at the implementation of the second API. The data flow that primarily returns the corresponding file:

[Route ("files/{name}/contents")] public httpresponsemessage Get (string name, String access_token) {                try {Validate (name, Access_token);                var file = Hostingenvironment.mappath ("~/app_data/" + name);                var responsemessage = new Httpresponsemessage (Httpstatuscode.ok);                var stream = new FileStream (file, FileMode.Open, FileAccess.Read);                Responsemessage.content = new Streamcontent (stream);                ResponseMessage.Content.Headers.ContentType = new Mediatypeheadervalue ("Application/octet-stream");            return responsemessage; } catch (Exception ex) {var errorresponsemessage = new Httpresponsemessage (Httpstatu                SCODE.INTERNALSERVERERROR); var stream = new MemoryStream (UTF8Encoding.Default.GetBytes (ex). Message??                ""));                Errorresponsemessage.content = new Streamcontent (stream); Return ERrorresponsemessage; }        }

The third API is to save the returned data stream to a physical file:

[Route ("files/{name}/contents")]        Public async void Post (string name, [Fromuri] string access_token)        {            var body = await Request.Content.ReadAsByteA Rrayasync ();            var appData = Hostingenvironment.mappath ("~/app_data/");            var fileext = name. Substring (name. LastIndexOf ('. ') + 1);            var outFile = Path.Combine (appdata,name);            File.writeallbytes (OutFile, body);        }

Now let's look at how to request Owas. That is, how the corresponding URL is generated.

For example, my owas server is owas.contoso.com. Then we'll be able to access Http://owas.contoso.com/hosting/discovery after we've configured the Owas.

  Here we take excel as an example    You see there's a view, edit, Mobileview three action. The app here is an Excel. We know the suffix of our physical files to find the appropriate app. In terms of the configuration of our system using edit or View action, it is assumed that pdf  we can only use the corresponding view. If the request is mobile-initiated, then we can only use Mobileview.   After we find the appropriate action, we get the corresponding URLSRC attribute, where the URL address we actually need is http://owas.contoso.com/x/_layouts/xlviewerinternal.aspx . Then get the code for this URL such as the following:

public class Linkcontroller:apicontroller {//<summary>//provides a link that can is used to Open a document in the relative Viewer///from the Office Web Apps server///</summary>/// <param name= "Filerequest" >indicates the request type</param>//<returns>a link usable for href&            Lt;/returns> public Link GetLink ([Fromuri] filerequest filerequest) {if (modelstate.isvalid)                {var xml = webconfigurationmanager.appsettings["Appdiscoveryxml"];                var wopiserver = webconfigurationmanager.appsettings["Appwopiserver"];                BOOL updateenabled = false; bool.                TryParse (webconfigurationmanager.appsettings["updateenabled"], out updateenabled);                Wopiapphelper wopihelper = new Wopiapphelper (Hostingenvironment.mappath (XML), updateenabled); var result = Wopihelper.getdocumentlink (Wopiserver + filerequeSt.name);                var rv = new Link {Url = result};            return RV;        } throw new ApplicationException ("Invalid modelstate");        }}public class Wopiapphelper {string _discoveryfile;        BOOL _updateenabled = false;        Wopihost.wopidiscovery _wopidiscovery;            Public Wopiapphelper (String discoveryxml) {_discoveryfile = Discoveryxml; using (StreamReader file = new StreamReader (discoveryxml)) {XmlSerializer reader = new Xmlseria                Lizer (typeof (Wopihost.wopidiscovery)); var wopidiscovery = reader.                Deserialize (file) as Wopihost.wopidiscovery;            _wopidiscovery = Wopidiscovery;            }} public Wopiapphelper (string discoveryxml, bool updateenabled): This (discoveryxml) {        _updateenabled = updateenabled; } public Wopihost.wopidiscoverynetZoneapp Getzone (String AppName) {var RV = _wopidiscovery.netzone.app.where (c = = C.name = AppName). F            Irstordefault ();        return RV; public string Getdocumentlink (string wopihostandfile) {var fileName = Wopihostandfile.substrin            G (Wopihostandfile.lastindexof ('/') + 1);            var Accesstoken = GetToken (fileName);            var fileext = filename.substring (Filename.lastindexof ('. ') + 1); var Netzoneapp = _wopidiscovery.netzone.app.asenumerable (). Where (c = c.action.where (d = d.ext = = fileext).            Count () > 0);            var appName = Netzoneapp.firstordefault ();            if (null = = appName) throw new ArgumentException ("Invalid file extension" + Fileext);            var rv = Getdocumentlink (Appname.name, Fileext, Wopihostandfile, Accesstoken);        return RV;            The string GetToken (string fileName) {KeyGen KeyGen = new KeyGen (); var RV = keyGen.gethash (FileName);        Return Httputility.urlencode (RV); } const String S_wopihostformat = "{0}?"        Wopisrc={1}&access_token={2} "; Hack:const string s_wopihostformatpdf = "{0}?"        Pdfmode=1&wopisrc={1}&access_token={2} ";            public string Getdocumentlink (string appName, String fileextension, String wopihostandfile, String accesstoken) {            var wopihosturlsafe = Httputility.urlencode (Wopihostandfile.replace ("", "%20")); var appstuff = _wopidiscovery.netzone.app.where (c = = C.name = = appName).            FirstOrDefault ();            if (null = = Appstuff) throw new ApplicationException ("Can ' t locate App:" + appName); var action = _updateenabled?            "Edit": "View";            if (Appname.equals ("Wordpdf")) {action = "view";            } if (HttpContext.Current.Request.Browser.IsMobileDevice) {action = "Mobileview";        }    var appaction = AppStuff.action.Where (c = c.ext = = FileExtension && c.name = = action).            FirstOrDefault ();            if (null = = appaction) throw new ApplicationException ("Can ' t locate Urlsrc for:" + appName);            var endPoint = appAction.urlsrc.IndexOf ('? ');            var endaction = appAction.urlsrc.Substring (0, EndPoint);            string fullPath = null;                Hack:for PDF now just append wordpdf option ... if (Fileextension.contains ("PDF")) { FullPath = string.            Format (S_wopihostformatpdf, Endaction, Wopihosturlsafe, Accesstoken); } else {FullPath = string.            Format (S_wopihostformat, Endaction, Wopihosturlsafe, Accesstoken);        } return FullPath; }    }

The corresponding configuration such as the following:

Appdiscoveryxml is a data file produced by our Owas (http://owas.contoso.com/hosting/discovery). Appwopiserver says our Owas is going to visit interface address. UpdateEnabled mainly indicates whether Owas can change our documentation, assuming true our action above uses edit, which uses view for false.

Apphmackey is just a key to data encryption. The generated URL

Note that the configuration here is updateenabled=true means that Owas is able to edit the file,

When we click on the browser to edit the results

Can be saved directly after the change:

Click on confirm to be able to save directly. The edit mode for pptx is as follows:

The edit mode of the Docx file here has been an error for a very long time did not fix. Error messages such as the following, let's say you know also please guide:

PDF is not in edit mode, and now look at Excel's read-only mode (view) such as the following:

"Edit in Browser" is not included in the menu. The 15th line is the new data I just changed.

The read-only mode of docx and pptx is not mapped, and the results of the mobile execution are as follows (I am visiting my website with my Android phone, because it is via WiFi to access the website on my computer, it is necessary to change the full name of the computer to an IP address).

Note that the URL above is 192.168.1.25XXX, where the IP is owas.contoso.com IP. Here is a summary of the test results such as the following:

View Edit Mobileview Remark
word through through
Excel Pass Pass Pass Under the HTTP and HTTPS protocols, both view and edit passed, and Mobileview only tested the HTTP protocol
Ppt Pass Pass Pass Under the HTTP and HTTPS protocols, both view and edit passed, and Mobileview only tested the HTTP protocol
Pdf Pass No edit action exists did not pass View is passed under the HTTP protocol, the HTTPS failed under the protocol, Mobileview failed

Here I put the focus of the question on Word's edit, the reason why the PDF has not been investigated in Owas with HTTPS and cannot be interviewed on mobile. The revolutionary predecessors who know these questions are also invited to advise.

Source code: http://download.csdn.net/detail/dz45693/7215395

Https://code.msdn.microsoft.com/office/Building-an-Office-Web-f98650d6

Integration of ASP and Office Web apps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.