在 WPF 应用程序中托管 WCF Web 服务 [英] Hosting WCF web service inside WPF application

查看:25
本文介绍了在 WPF 应用程序中托管 WCF Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 WPF 应用程序.作为应用程序的一部分,我需要通过另一个 iOS 应用程序接收一些图像.因此,我已经编写了 WCF REST 服务和 iOS,并且我能够仅当我将该服务定义为 IIS 的一部分时将图像发送到 Web 服务.
我需要做的是:当 WPF 应用程序启动时,Web 服务也将启动,并公开一个端口号供 iOS 设备发送图像并在启动时唤醒"WPF 应用程序.有什么想法吗?

I am developing a WPF application. As part of the application, I need to receive some images via another iOS application. And so I've written both WCF REST service and the iOS and I am able to send the images to the web service only when I define the service as part of IIS.
What I need to be happening is: When the WPF application is started, the web service will also be started as well, and expose a port number for the iOS device to send images and "wake" the WPF application when started. Any thoughts?

推荐答案

是的,我做到了.实际上正如蒂姆所说,这正是我所做的自托管服务.您可以查看以下视频(还有很多其他视频,请查看链接).http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF/

Yes I did. Actually as Tim mentioned, that exactly what I did self-hosting service. You can take a look at the following video (there are plenty of other, have a look at the links). http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF/

以下是我的 WCF 项目中的完整文件:(如电影中所述),我希望它能帮助您入门..请注意,在您的机器中打开特定端口以启用传入的 HTTP 流量也很重要.查看 WCF ServiceHost 访问权限.

Here are the complete files in my WCF project: (as mention in the movie), I hope it will get you started.. Just note that it is also important to open a specific port in you machine to enable incoming HTTP traffic. Have a look at WCF ServiceHost access rights.

Eval.cs

[DataContract]
public class Eval
{
    public string id;

    [DataMember]
    public string Submitter;
    [DataMember]
    public DateTime Timesent;
    [DataMember]
    public string Comments;
}

IEvalService.cs

[ServiceContract]
public interface IEvalService
{
    [WebInvoke(Method="POST", UriTemplate = "evals")]
    [OperationContract]
    void SubmitEval(Eval i_Eval);

    [WebGet(UriTemplate = "evals")]
    [OperationContract]
    List<Eval> GetEvals();

    [WebGet(UriTemplate="eval/{i_Id}")]
    [OperationContract]
    Eval GetEval(string i_Id);

    [WebGet(UriTemplate = "evals/{i_Submitter}")]
    [OperationContract]
    List<Eval> GetEvalsBySubmitters(string i_Submitter);

    [WebInvoke(Method = "DELETE", UriTemplate = "eval/{i_Id}")]
    [OperationContract]
    void RemoveEval(string i_Id);

    [WebGet(UriTemplate = "GetLastPhoto", BodyStyle = WebMessageBodyStyle.Bare)]
    Stream GetLastPhoto();

    [OperationContract] // this web address is for receiving the image for the iOS app.
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "TestPost")]
    string TestPost(Stream stream);
}

EvalService.cs

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class EvalService : IEvalService
{
    private List<Eval> m_Evals = new List<Eval>();
    private int evalCount = 0;
    private string k_FilePath = "C:\\ImageUpload\\";

    public static event Action<LogicImage> ImageLoaded;

    public void SubmitEval(Eval i_Eval)
    {
        i_Eval.id = (++evalCount).ToString();
        m_Evals.Add(i_Eval);
    }

    public List<Eval> GetEvals()
    {
        return m_Evals;
    }

    public Eval GetEval(string i_Id)
    {
        return m_Evals.First(e => e.id.Equals(i_Id));
    }

    public List<Eval> GetEvalsBySubmitters(string i_Submitter)
    {
        if (i_Submitter == null && i_Submitter.Equals(""))
        {
            return null;
        }

        else
        {
            return m_Evals.Where(e => e.Submitter == i_Submitter).ToList();
        }
    }

    public void RemoveEval(string i_ID)
    {
        throw new NotImplementedException();
    }

    public Stream GetLastPhoto()
    {
        Image image = Image.FromFile("C:\\ImageUpload\\014.png");
        MemoryStream ms = new MemoryStream(imageToByteArray(image));
        return ms;
    }

    public string TestPost(Stream stream)
    {
        HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

        if (parser.Success)
        {
            if (parser.Success)
            {
                // deal with exceptions..
                //
                File.WriteAllBytes(k_FilePath + parser.Filename, parser.FileContents);
                if (ImageLoaded != null)
                {
                    ImageLoaded.Invoke(new LogicImage(){FileName = parser.Filename, Location = k_FilePath});
                }
            }
        }

        return "test";
    }

    public static byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }
}

public class LogicImage
{
    public string FileName { get; set; }
    public string Location { get; set; }
}

最后但并非最不重要的 ** App.config**

And last but not least ** App.config**

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="ImageRecevierWebService.EvalService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/ImageRecevierWebService/Service1/"/>
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" contract="ImageRecevierWebService.IEvalService">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

这篇关于在 WPF 应用程序中托管 WCF Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆