无法将图像上载到WCF Rest服务
我正在创建一个WCF Rest服务,用于从移动应用程序上载图像。但是我越来越 远程服务器返回错误:(400)请求错误。谁能指出我做错了什么。 以下是我的定义:无法将图像上载到WCF Rest服务,wcf,rest,post,image-upload,Wcf,Rest,Post,Image Upload,我正在创建一个WCF Rest服务,用于从移动应用程序上载图像。但是我越来越 远程服务器返回错误:(400)请求错误。谁能指出我做错了什么。 以下是我的定义: [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostImage",Method ="POST")] PublicMessage PostImage(Upload obj); [DataCont
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostImage",Method ="POST")]
PublicMessage PostImage(Upload obj);
[DataContract]
public class Upload
{
[DataMember]
public Stream File { get; set; }
}
服务定义:
public PublicMessage PostImage(Upload obj)
{
byte[] buffer = StreamToByte(obj.File); //Function to convert the stream to byte array
FileStream fs = new FileStream(@"D:\ShopMonkeyApp\Desert.jpg", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffer);
bw.Close();
return new PublicMessage { Message = "Recieved the image on server" };
}
客户端应用程序:
string filePath = @"D:\ShopMonkeyApp\Desert.jpg";
string url = "http://localhost:50268/shopmonkey.svc/PostImage/"; // Service Hosted in IIS
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/xml";
request.Method = "POST";
request.ContentType = "image/jpeg";
using (Stream fileStream = File.OpenRead(filePath))
using (Stream requestStream = request.GetRequestStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
string result;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
Web配置:
<system.serviceModel>
<services>
<service name="ShopMonkey.ShopMonkey" behaviorConfiguration="ServiceBehaviour">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address ="" binding="webHttpBinding" contract="ShopMonkey.IShopMonkey" behaviorConfiguration="web">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.behaviorConfiguration="web"
-->
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
<dataContractSerializer maxItemsInObjectGraph="10000000"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
谢谢
Vijay如果上载类上没有任何其他属性,请将WCF服务方法更改为具有流参数,而不是将其包装到类中,如下所示:
[OperationContract]
[WebInvoke(UriTemplate = "/PostImage",Method ="POST")]
PublicMessage PostImage(Stream obj);
private string ClientSample()
{
var uploadObject = new Upload();
Image image = Image.FromFile(@"D:\ShopMonkeyApp\Desert.jpg");
MemoryStream ms = new MemoryStream();
uploadObject.FileContent = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(uploadObject.FileContent);
ms.Close();
string responseMessage = null;
var request = WebRequest.Create(http://localhost:50268/shopmonkey.svc/PostImage) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = method;
}
if(method == "POST" && requestBody != null)
{
byte[] requestBodyBytes;
requestBodyBytes = ToByteArrayUsingDataContractSer<Upload>(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
}
private static byte[] ToByteArrayUsingDataContractSer<T>(T requestBody)
{
byte[] bytes = null;
var serializer1 = new DataContractSerializer(typeof(T));
var ms1 = new MemoryStream();
serializer1.WriteObject(ms1, requestBody);
ms1.Position = 0;
var reader = new StreamReader(ms1);
bytes = ms1.ToArray();
return bytes;
}
然后,您可以使用WebClient类直接上载文件,如下所示:
var c = new System.Net.WebClient();
c.OpenWrite(string.Concat("http://localhost:50268/shopmonkey.svc", "/PostImage"), "POST");
c.Headers[HttpRequestHeader.ContentType] = "image/jpeg";
return c.UploadFile(string.Concat(serviceBaseUrl, resourceUrl), filePath);
也请参考此
更新:
请在下面查找示例以使代码正常工作:
[OperationContract]
[WebInvoke(UriTemplate = "/PostImage",Method ="POST")]
PublicMessage PostImage(Upload obj);
[DataContract]
public class Upload
{
[DataMember]
public MemoryStream FileContent { get; set; }
}
现在,实现PostImage的方法如下所示:
public PublicMessage PostImage(Upload obj)
{
byte[] buffer = new byte[obj.FileContent.Length];
using (FileStream ms = new FileStream(@"D:\ShopMonkeyApp\Temp\Desert.jpg", FileMode.OpenOrCreate))
{
obj.FileContent.Position = 0;
int read = fileInfo.Content.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, read);
}
return new PublicMessage { Message = "Recieved the image on server" };
}
现在,由于我们的服务器端代码已完成,现在移动到将文件上载到服务器的客户端部分,如下所示:
[OperationContract]
[WebInvoke(UriTemplate = "/PostImage",Method ="POST")]
PublicMessage PostImage(Stream obj);
private string ClientSample()
{
var uploadObject = new Upload();
Image image = Image.FromFile(@"D:\ShopMonkeyApp\Desert.jpg");
MemoryStream ms = new MemoryStream();
uploadObject.FileContent = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(uploadObject.FileContent);
ms.Close();
string responseMessage = null;
var request = WebRequest.Create(http://localhost:50268/shopmonkey.svc/PostImage) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = method;
}
if(method == "POST" && requestBody != null)
{
byte[] requestBodyBytes;
requestBodyBytes = ToByteArrayUsingDataContractSer<Upload>(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
}
private static byte[] ToByteArrayUsingDataContractSer<T>(T requestBody)
{
byte[] bytes = null;
var serializer1 = new DataContractSerializer(typeof(T));
var ms1 = new MemoryStream();
serializer1.WriteObject(ms1, requestBody);
ms1.Position = 0;
var reader = new StreamReader(ms1);
bytes = ms1.ToArray();
return bytes;
}
私有字符串ClientSample()
{
var uploadObject=new Upload();
Image=Image.FromFile(@“D:\ShopMonkeyApp\Desert.jpg”);
MemoryStream ms=新的MemoryStream();
uploadObject.FileContent=新建MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(uploadObject.FileContent);
Close女士();
字符串responseMessage=null;
var request=WebRequest.Create(http://localhost:50268/shopmonkey.svc/PostImage)作为HttpWebRequest;
if(请求!=null)
{
request.ContentType=“应用程序/xml”;
request.Method=Method;
}
if(方法==“POST”&&requestBody!=null)
{
字节[]请求体字节;
requestBodyBytes=ToByteArrayUsingDataContractSer(requestBody);
request.ContentLength=requestBodyBytes.Length;
使用(Stream postStream=request.GetRequestStream())
写(requestBodyBytes,0,requestBodyBytes.Length);
}
if(请求!=null)
{
var response=request.GetResponse()作为HttpWebResponse;
if(response.StatusCode==HttpStatusCode.OK)
{
Stream responseStream=response.GetResponseStream();
if(responseStream!=null)
{
变量读取器=新的StreamReader(responseStream);
responseMessage=reader.ReadToEnd();
}
}
其他的
{
responseMessage=response.StatusDescription;
}
}
}
私有静态字节[]ToByteArrayUsingDataContractSer(T requestBody)
{
字节[]字节=null;
var serializer1=新的DataContractSerializer(typeof(T));
var ms1=新内存流();
serializer1.WriteObject(ms1,requestBody);
ms1.位置=0;
变量读取器=新的流读取器(ms1);
字节=ms1.ToArray();
返回字节;
}
注意:确保客户端和服务器上的上载对象都定义了相同的命名空间和属性,以避免任何反序列化问题。在web.config中增加消息队列长度可以解决我的问题
<webHttpBinding>
<binding name="streamWebHttpbinding" transferMode="Streamed" maxReceivedMessageSize="1000000000000" receiveTimeout="01:00:00" sendTimeout="01:00:00" />
</webHttpBinding>
感谢所有还请清理您的代码示例-缩进非常糟糕,客户端代码中存在明显的c#错误,这将阻止它在当前状态下编译。请尝试删除正文样式,看看它是否有效。另外,请发布你的StreamToByte方法是什么样子的?我已经用示例代码更新了我的答案。很抱歉延迟。请尝试以下操作:嗨,rajesh,我已经尝试了你的代码,但我仍然收到远程服务器返回的错误:(400)错误请求。还有其他方法吗?您尝试上载的图像大小是多少?谢谢您的回复。图像大小是826kb。是否需要在web.config文件中进行特殊设置?请让我知道..在您的服务上启用跟踪(),并检查日志文件以了解400错误请求背后的原因。主要是由于webHttpBinding.rajesh的大小,因此增加了您的readerQuotas设置。现在它正在工作。我已经在web.config中增加了消息队列长度。但是上传的图像在打开时显示错误。您能告诉我流到图片转换中的任何错误吗?。工作非常好。谢谢:)