次のように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' も持っています。GET 操作は本体を持つことができません。パラメータ 'width' を 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:
が無効です。