我试图从 wcf 休息服务中获取图像,如下所示:
[ServiceContract]
public interface IReceiveData
{
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "picture/")]
//this line is wrong though
Stream GetImage(int width, int height);
}
public class RawDataService : IReceiveData
{
public Stream GetImage(int width, int height)
{
// Although this method returns a jpeg, it can be
// modified to return any data you want within the stream
Bitmap bitmap = new Bitmap(width, height);
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);
}
}
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return ms;
}
}
在我的主机应用程序中:
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(RawDataService), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(IReceiveData), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
host.Open(); // this line
Console.WriteLine("Host opened");
Console.ReadLine();
我收到此错误:
合约“IReceiveData”中的“GetImage”操作使用 GET,但也有主体参数“width”。GET 操作不能有主体。将参数“宽度”设为 UriTemplate 参数,或从 WebGetAttribute 切换到 WebInvokeAttribute。
我不确定您如何为图像设置 webinvoke/UriTemplate 方法或如何获取图像并返回它。有人可以在此示例中发布显示图像的正确方法吗?
编辑
如果我在导航到时尝试以下答案并UriTemplate = "picture?w={width}&h={height}"
用作我的 UriTemplate,http://www.localhost.com:8000/Service/picture?width=50&height=40
则会在我的代码中收到错误:
public Stream GetImage(int width, int height)
{
Bitmap bitmap = new Bitmap(width, height); // this line
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);
}
}
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return ms;
}
哪个状态ArguementException was unhandled by user code:
参数无效。