我正在尝试从WCF REST服务获取图片,方法如下:
[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’的body参数。 GET操作不能有body。要么将参数‘width’设置为UriTemplate参数,要么从WebGetAttribute切换到WebInvokeAttribute。”
我不确定如何为图像设置webinvoke / UriTemplate方法,也不知道如何获取并返回图像。可以有人发布在此示例中正确显示图像的方法吗?
编辑
如果我尝试下面的答案并在导航到`http://www.localhost.com:8000/Service/picture?width=50&height=40`时使用`UriTemplate ="picture?w={width}&h={height}"`作为我的UriTemplate,我会在代码中收到一个错误。
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;
}
出现了参数异常未被用户代码处理:
参数无效。
在合同'IReceiveData'中,操作'GetImage'具有名为'width'的路径变量,其类型不是'string'。UriTemplate路径段的变量必须具有'type 'string'。
- G Grint
改为string
了。URL 没有区分参数是int
还是string
的概念,因此所有内容都将作为string
传递,并且您需要根据您的代码验证和转换值。无论如何,我的解决方案是正确的答案,因为我在我的一个应用程序中也有完全相同的运行 :-D - Thorsten Dittmar/picture
,然后获取一个默认尺寸的图片?这可以通过添加另一个方法来实现,该方法不带参数并调用return GetPicture("640", "480");
。 在上面的代码中,当然你会抛出异常或其他错误而不是设置默认尺寸。我只是这样做是为了让人们在出现错误时能看到一些东西正在发生。 - Thorsten Dittmarpicture/
。 - Thorsten Dittmar