繁体   English   中英

使用Silverlight的REST服务时遇到问题

[英]Problem consuming a REST service from Silverlight

在我的Web项目中,我有一个包含REST服务的TestStreamingService.svc文件。

服务合同:

[ServiceContract(Namespace = "")]
    public interface ITestStreamingService
    {
        [OperationContract]
        [WebGet(UriTemplate = "Download?file={file}&size={size}")] //file irrelevant, size = returned size of the download
        Stream Download(string file, long size);

        [OperationContract]
        [WebInvoke(UriTemplate= "Upload?file={file}&size={size}", Method = "POST")]
        void Upload(string file, long size, Stream fileContent);

        [OperationContract(AsyncPattern=true)]
        [WebInvoke(UriTemplate = "BeginAsyncUpload?file={file}", Method = "POST")]
        IAsyncResult BeginAsyncUpload(string file, Stream data, AsyncCallback callback, object asyncState);

        void EndAsyncUpload(IAsyncResult ar);

    } 

服务实现(* .svc文件)

使用系统; 使用System.IO; 使用System.ServiceModel; 使用System.ServiceModel.Activation; 使用ICode.SHF.Tests;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]公共类TestStreamingService:ITestStreamingService {

public Stream Download(string file, long size)
{
    return new SHFTestStream(size);
}

public void Upload(string file, long size, Stream fileContent)
{            
    FileInfo f = new FileInfo(String.Format(@"C:\{0}", file));

    using (FileStream fs = f.Create())
    {
        CopyStream(fileContent, fs);
        fs.Flush();
        fs.Close();
    }
}

public IAsyncResult BeginAsyncUpload(string file, Stream data, AsyncCallback callback, object asyncState)
{
    return new CompletedAsyncResult<Stream>(data, file);
}

public void EndAsyncUpload(IAsyncResult ar)
{
    Stream data = ((CompletedAsyncResult<Stream>)ar).Data;
    string file = ((CompletedAsyncResult<Stream>)ar).File;
    StreamToFile(data, file);
}

private void StreamToFile(Stream data, string file)
{
    string subDir = Guid.NewGuid().ToString("N");
    string uploadDir = Path.Combine(Path.GetDirectoryName(typeof(TestStreamingService).Assembly.Location), subDir);
    Directory.CreateDirectory(uploadDir);

    byte[] buff = new byte[0x10000];

    using (FileStream fs = new FileStream(Path.Combine(uploadDir, file), FileMode.Create))
    {
        int bytesRead = data.Read(buff, 0, buff.Length);
        while (bytesRead > 0)
        {
            fs.Write(buff, 0, bytesRead);
            bytesRead = data.Read(buff, 0, buff.Length);
        }
    }
}

}

公共类CompletedAsyncResult:IAsyncResult {T数据;

string file;

public CompletedAsyncResult(T data, string file)
{ this.data = data; this.file = file; }

public T Data
{ get { return data; } }

public string File
{ get { return file; } }

#region IAsyncResult Members

public object AsyncState
{
    get { return (object)data; }
}

public System.Threading.WaitHandle AsyncWaitHandle
{
    get { throw new NotImplementedException(); }
}

public bool CompletedSynchronously
{
    get { return true; }
}

public bool IsCompleted
{
    get { return true; }
}

#endregion

}

我的Web.Config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

    <system.serviceModel>
        <behaviors>          
            <serviceBehaviors>
                <behavior name="">                  
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>              
            </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="REST">
              <webHttp/>             
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <bindings>
            <webHttpBinding>
                <binding name="ICode.SHF.SL.Tests.Web.TestStreamingService.customBinding0"/>                                                        
            </webHttpBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            />
        <services>          
            <service name="ICode.SHF.SL.Tests.Web.TestStreamingService">
              <host>
                <baseAddresses>
                  <add baseAddress="http://localhost:40000/Streaming"/>
                </baseAddresses>
              </host>
                <endpoint name="TestStreamingEndpoint" address="RESTService" binding="webHttpBinding" bindingConfiguration="ICode.SHF.SL.Tests.Web.TestStreamingService.customBinding0"
                    contract="ICode.SHF.SL.Tests.Web.ITestStreamingService" behaviorConfiguration="REST"/>

                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />                
            </service>
        </services>
    </system.serviceModel>  
</configuration>

我试图通过WebClient从Silverlight(Web项目包含clientaccesspolicy.xml)使用服务,但是我似乎失败了,Fiddler不会显示正在进行的任何调用。

(使用WebClient.OpenWriteAsync(用于上传)和OpenReadAsync(用于下载))

客户端使用的uri为:“ http:// localhost:40000 / Streaming / Service / Download?file = xxx&size = 65536”

当我在IE中使用以下uri时:“ http:// localhost:40000 / TestStreamingService.svc / Download?file = xxx&size = 65536”,下载操作开始,下载的文件与传递的大小匹配。

我在WebClient中使用IE uri并没有成功。

谁能告诉我我在做什么错? 看来我错过了一些基本知识...

您的网站需要身份验证吗? 至于提琴手,请尝试将您的网络客户端连接到:

http://localhost.:40000/Streaming/Service/Download?file=xxx&size=65536

(请注意localhost后的多余点)

看来我已经设法解决了有关从Silverlight通过下载功能的问题。 WebClient。

这就是我所做的。

  1. 将服务合同和实施移至单独的项目MyWCFLibrary(WCF服务库)
  2. 在托管项目的ASP.NET网站中添加了上述库的引用
  3. 添加了一个文本文件“ Service.svc”并对其进行了编辑:

    <%@ ServiceHost语言=“ C#” Debug =“ true” Service =“ MyWCFLibrary.TestStreamingService” Factory =“ System.ServiceModel.Activation.WebServiceHostFactory”%>

  4. 修改了WebClient操作的uri以匹配* .svc文件

似乎有效。

我仍在尝试弄清楚一件事,因此欢迎发表评论:

我可以这样通过Webclient在服务上执行操作:

WebClient wc = new WebClient();
 string uri = String.Format("http://localhost.:40000/Service.svc/Download?file=xxx&size={0}", size);
                wc.OpenReadAsync(new Uri(uri));

但不是这样的:

 string uri = String.Format("http://localhost.:40000/Services/StreamingService/Download?file=xxx&size={0}", size);
                wc.OpenReadAsync(new Uri(uri));

其中:localhost:40000 / Services是服务的基地址,StreamingService是端点的地址(我的WebConfig中的最新更改)

谁能解释为什么? 还是我默认使用第一个uri?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM