身体参数';宽度';.GET操作不能有正文
本文关键字:不能 正文 操作 GET 宽度 参数 | 更新日期: 2023-09-27 18:30:03
我正试图从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,但也具有body参数"width"。GET操作不能有正文。要么制作参数"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;
}
表示ArguementException was unhandled by user code:
参数无效
在属性中,您需要告诉运行时您期望将宽度和高度作为URL参数。
目前,运行时假设您调用的URL没有参数,但被调用的方法需要参数,因此运行时真的不知道如何找到传递给width
和height
方法的值。
这看起来像
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "picture/{width}/{height}")]
Stream GetImage(string width, string height)
{
int w, h;
if (!Int32.TryParse(width, out w))
{
// Handle error: use default values
w = 640;
}
if (!Int32.TryParse(height, out h))
{
// Handle error use default values
h = 480;
}
....
}
您将需要调用类似http://test.tld/picture/320/200
的URL。
UriTemplate = "picture/"
应该是类似的东西
UriTemplate = "picture?w={width}&h={height}"
此命令告诉WCF如何从URL获取宽度和高度参数。