English 中文(简体)
RESTful WCF Service that Needs to Uploadations And Multi Arguments
原标题:RESTful WCF Service That Needs to Upload Images And Multiple Arguments
  • 时间:2011-08-01 22:10:17
  •  标签:
  • .net
  • wcf
  • rest

I am in the process of developing a WCF service that needs to take in an image and 2 parameters. One being an int type, the other a string array. So this would be easy enough if it were only 1 parameter to send up, along with the image:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadImages/{imageID}")]
public void UploadImages(int imageID, Stream image)
{                       
}

现在,在这种情形下,形象就出现在员额的身上。 如果服务行业的消费者需要采纳第三批数据,那么这一调查如何看待和工作如何?

  <system.serviceModel>
    <client>
    </client>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingStreamed" transferMode="Streamed"></binding>
      </webHttpBinding>      
    </bindings>
    <services> 
      <service name="ImageService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="MyWebHttpBehavior"  name="ImageServiceWebBinding" contract=IImageService" />
      </service>
    </services>
    <behaviors>      
      <endpointBehaviors>          
        <behavior name="MyWebHttpBehavior">
          <customWebHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="customWebHttp" type="CustomHttpBehaviorExtensionElement, ImageUploader" />
      </behaviorExtensions>
    </extensions>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
最佳回答

You can pass the additional parameters in the URI as well, like in the example below. Or you can pass them as HTTP headers and fetch them using the WebOperationContext.Current.IncomingRequest.Headers property.

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadImages/{fileName}?imageId={imageID}")]
public void UploadImages(int imageID, string fileName, Stream image)
{                       
}

<>Update>

即使参数类型是阵列,你也可以通过座标,但你需要提供<代码>。 QueryStringConver,其中可以编码这种编号。 以下例子表明:

public class StackOverflow_6905108
{
    [ServiceContract]
    public class Service
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "UploadImages/{fileName}?array={array}")]
        public void UploadImages(int[] array, string fileName, Stream image)
        {
            Console.WriteLine("Array:");
            foreach (var item in array) Console.Write("{0} ", item);
            Console.WriteLine();
        }
    }
    public static void SendPost(string uri, string contentType, string body)
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.Method = "POST";
        req.ContentType = contentType;
        Stream reqStream = req.GetRequestStream();
        byte[] reqBytes = Encoding.UTF8.GetBytes(body);
        reqStream.Write(reqBytes, 0, reqBytes.Length);
        reqStream.Close();

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException e)
        {
            resp = (HttpWebResponse)e.Response;
        }

        Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        foreach (string headerName in resp.Headers.AllKeys)
        {
            Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
        }
        Console.WriteLine();
        Stream respStream = resp.GetResponseStream();
        Console.WriteLine(new StreamReader(respStream).ReadToEnd());

        Console.WriteLine();
        Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
        Console.WriteLine();
    }
    class MyQueryStringConverter : QueryStringConverter
    {
        QueryStringConverter originalConverter;
        public MyQueryStringConverter(QueryStringConverter originalConverter)
        {
            this.originalConverter = originalConverter;
        }
        public override bool CanConvert(Type type)
        {
            return type == typeof(int[]) || base.CanConvert(type);
        }
        public override object ConvertStringToValue(string parameter, Type parameterType)
        {
            if (parameterType == typeof(int[]))
            {
                return parameter.Split( , ).Select(x => int.Parse(x)).ToArray();
            }
            else
            {
                return base.ConvertStringToValue(parameter, parameterType);
            }
        }
    }
    public class MyWebHttpBehavior : WebHttpBehavior
    {
        protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
        {
            return new MyQueryStringConverter(base.GetQueryStringConverter(operationDescription));
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "").Behaviors.Add(new MyWebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        SendPost(baseAddress + "/UploadImages/a.txt?array=1,2,3,4", "application/octet-stream", "The file contents");

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
问题回答

暂无回答




相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签