WCF rest work summary (2)

Source: Internet
Author: User

In the previous article, we set up the WCF rest service level and sent the GET request in three ways to achieve the ability to get JSON. If you haven't seen it, You can first take a look at it-rest work summary 1

Today, I mainly write down post and other methods for sending requests and uploading and downloading files in stream mode.

 

I. Post submit data

Let's take a look at the different get methods of post and get. Let's pass parameters through URL. Let's take a look at our creation method.

 

 
[Webinvoke (uritemplate ="Tasks/Add", Method ="Post", Requestformat = webmessageformat. JSON)]
VoidCreate (pocotask );

We need to accept an object class in JSON format. This occurs again. The above problem occurs again. Our client does not have an object class and Cannot serialize the object class to JSON. Do we need to splice the JSON by ourselves? Of course not. It's so painful.

Here we recommend JSON. net. There are two classes that can help us to convert a single object and convert a set object: jobject and jarray.

After declaring these two classes, we can get the JSON format of tostring. It's very convenient ~ ViewCode

Here, you do not need to write dynamic statements like annotations. This way, even if the server does not support. net4.0, it can be used.

Now that you know how to construct the data submitted by post, start to implement post submission ~ The Code on is still compared in three ways.

These three methods are recommended. The third method is the latest. net4.5 integrated access to rest is very convenient because it supports direct put and delete requests.

It is tailored for rest ~~ Check the put request.

Note the following:Because we are sending JSON, no matter which method of sending the request, remember to set contenttype = application/JSON

Otherwise, an HTTP 400 error will be thrown. 400-many of the requests with errors are caused by incorrect client requests. Therefore, if 400 errors occur, check the client requests.

Because put, delete, and post are basically the same, I don't need code anymore.

Ii. upload and download rest files

Upload and download stream files

First, let's look at the interface and Implementation of the server.

We need to implement three functions

1. display an image

2. Download an object

3. upload an object

Show the image implementation code first.

This is relatively simple to open directly in the browser. Remember to set the output contenttype. Sometimes we want to open another format. Here, there is a small method to get the output contenttype Based on the file extension.

That is, the getcontenttype method used above is found in the knowledge base of the garden.

The client directly references the connection.

2. Download

The above shows the file directly in the browser. If we want to download resources, the method is as simple as the previous method.

File Download

  Public   Void Getexecl (String Execlname)
{
String Folder = system. Web. Hosting. hostingenvironment. mappath ( " ~ /Files " );
VaR Fullfilename = path. Combine (folder, execlname );
If (File. exists (fullfilename ))
{
Fileinfo downloadfile = New Fileinfo (fullfilename );
Httpcontext. Current. response. Clear ();
Httpcontext. Current. response. clearheaders ();
Httpcontext. Current. response. Buffer = False ;
Httpcontext. Current. response. contenttype = " Application/octet-stream " ;
Httpcontext. Current. response. appendheader ( " Content-Disposition " , " Attachment; filename = " + Httputility. urlencode (downloadfile. fullname, system. Text. encoding. ASCII ));
Httpcontext. Current. response. appendheader ( " Content-Length " , Downloadfile. length. tostring ());
Httpcontext. Current. response. writefile (downloadfile. fullname );

Httpcontext. Current. response. Flush ();
Httpcontext. Current. response. End ();
}
}

3.Upload
This file upload is the key point to be discussed. It has been a long time ~

First, remember to use the rest template to configure the configuration file as follows:

   <  System. servicemodel  > 
< Servicehostingenvironment Aspnetcompatibilityenabled = "True" />
< Standardendpoints >
< Webhttpendpoint >
<! --
Configure the WCF rest service base address via the Global. asax. CS file and the default endpoint
Via the attributes on the <standardendpoint> element below
-->
< Standardendpoint Name = "" Maxcompute edmessagesize = "3000000" Defaultoutgoingresponseformat = "JSON" Helpenabled = "True" Automaticformatselectionenabled = "True" >
< Readerquotas Maxarraylength = "300000" />
</ Standardendpoint >

</ Webhttpendpoint >
</ Standardendpoints >
</ System. servicemodel >

In this way, you can upload large files.

Client-side upload is simple with httpclient

I wrote that the upload was very simple, but it took a long time to complete the results.

Let's talk about the previous writing method.

In the past, this was successful. Who knows that an error was reported when I moved to rest WCF this time and found that stream. Length cannot be read.I would like to ask you here ~ Why is an error reported when reading stream. length?

Fangxinggood of csdn has explained this. Thank you very much.

Because it is encapsulated into messagebodystream, length is not supported, just like the data in WCF streamed. In WCF, the client transmits data to the server and receives data. When I/O is started on the server, the stream is not completely transmitted, so messagebodystream does not support length. However, HTTP is used for rest, so all streams have arrived at the server. To get the length, use: var Len = weboperationcontext. Current. incomingrequest. contentlength.

Finally, an HTTP 400 error will be thrown.

I had to replace another method. This method does not require length.

However, it is found that an error is reported during conversion to byte.The input is not a valid base-64 string because it contains non-base-64 characters, more than two filling characters, or contains non-blank characters between filling characters.

Why? Hope you can tell me

SolutionSolution

Later, Google found another method to get the length in the WCF rest so that the first method could be used.

Put

Long bytelength = stream. length;

Change

Long bytelength = weboperationcontext. Current. incomingrequest. contentlength;

In this way, we can get the length and solve the upload problem ~~

Here, if you upload an image, there is a very simple method. The core code is simply two lines ~

3. Session and cookie

Session can be used in WCF, but it seems that session cannot be used in rest WCF. I checked some information and found no way to use session.

It may be because the use of session will allow coupling between the server and the client. Later found the rest common misunderstanding http://www.prescod.net/rest/mistakes/

It mentioned that a session is irrelevant.

Cookie can still be used normally. Here we can say that the client's method of reading cookies does not seem to be able to read the WebClient's method of using more flexible httpwebrequest.

These two statements

Cookiecontainer cookie = new cookiecontainer ();
Request. cookiecontainer = cookie;

Iv. Summary

I am doing this and share my experience with you. I hope you will be able to answer your questions ~~

Rest WCF reflects Roa's resource-oriented programming. It feels better to decouple the client and the server, and call the rest service is also simple. A lot of efficiency without proxy also improves the way you like this style.

Refer:

Http://blog.csdn.net/fangxinggood/article/details/6235662

Original article:

Http://www.cnblogs.com/wlflovenet/archive/2011/10/28/WCFREST2.html

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.