我試着從一個WCF休息服務中獲得的圖像,像這樣:身體參數'寬度'。 GET操作不能有正文?
[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();
我得到這個錯誤:
Operation 'GetImage' in contract 'IReceiveData' uses GET, but also has body parameter 'width'. GET operations cannot have a body. Either make the parameter 'width' a UriTemplate parameter, or switch from WebGetAttribute to 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:
參數無效。
您的方法返回:'合同'IReceiveData'中的Operation'GetImage'有一個名爲'width'的路徑變量,它沒有'string'類型。 UriTemplate路徑段的變量必須有'string'類型。' – 2012-04-04 14:24:59
你說得對,我忘記把'int'改成'string'。一個URL沒有關於參數是一個'int'還是一個'string'的概念,所以所有東西都以'string'的形式傳遞,你需要相應地驗證和轉換你的代碼中的值。無論如何,我的解決方案是正確的答案,因爲我也正在運行在我的一個應用程序中:-D – 2012-04-04 14:57:41
好的,我會再次更新我的答案,以清楚說明*當然是行//處理錯誤'應該換成一些代碼來處理錯誤... – 2012-04-04 15:17:33