尝试上传文件时,WCF休息服务访问被拒绝了吗?

时间:2014-07-15 09:56:48

标签: asp.net web-services wcf file-upload wcf-rest

我提供了一个WCF restful服务,用于将文件上传到服务器上的特定目录,一个可以上传文件的小型ASP.NET Web应用程序抛出了这个Web服务。问题是我经常收到拒绝访问的错误。我试图将所有权限授予用于测试目的的文件夹(对每个人的完全控制,对IIS_IUSRS的完全控制,WCF和Web服务的AppPool等),但仍然显示相同的错误。以下是服务和Web应用程序的代码:

主要WCF服务类

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
                 InstanceContextMode = InstanceContextMode.PerCall,
                 IgnoreExtensionDataObject = true,
                 IncludeExceptionDetailInFaults = true)]
    public class UploadFile : IUploadFile
    {
        public ReturnValue ExcelUpload(Stream File)
        {
            using (FileStream writer = new FileStream(@"C:\Users\Public\Documents", FileMode.Create))
            {
                int ReadCount = 0;
                var buffer = new byte[8192];
                while ((ReadCount = File.Read(buffer, 0, buffer.Length)) != 0)
                {
                    writer.Write(buffer, 0, ReadCount);
                }
            }

            return new ReturnValue() { IsSuccessfull = true };
        }

        public ReturnValue test(int id)
        {
            return new ReturnValue() { IsSuccessfull = true };
        }
    }

WCF服务合同

[ServiceContract(Name = "ExcelUpload.IUploadFile")]
public interface IUploadFile
{
    [OperationContract]
    [DataContractFormat]
    [WebInvoke(Method = "*",
               UriTemplate = "UploadExcel/",
               BodyStyle = WebMessageBodyStyle.Bare,
               ResponseFormat = WebMessageFormat.Json)]
    ReturnValue ExcelUpload(Stream File);
    // TODO: Add your service operations here

    [OperationContract]
    [DataContractFormat]
    [WebInvoke(Method = "POST",
               UriTemplate = "test/",
               BodyStyle = WebMessageBodyStyle.Bare,
               ResponseFormat = WebMessageFormat.Json)]
    ReturnValue test(int id);
}


// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class ReturnValue
{
    [DataMember]
    public bool IsSuccessfull { get; set; }
}

WCF服务web.config

<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
      <serviceActivations>
        <add relativeAddress="~/UploadFile.svc" service="ExcelUpload.UploadFile"/>
      </serviceActivations>
    </serviceHostingEnvironment>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain"
                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647"
                 transferMode="Streamed"
                 sendTimeout="00:05:00" 
                 crossDomainScriptAccessEnabled="true">
          <readerQuotas  maxDepth="2147483647"
                         maxStringContentLength="2147483647"
                         maxArrayLength="2147483647"
                         maxBytesPerRead="2147483647"
                         maxNameTableCharCount="2147483647"/>
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="defaultServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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="true"/>
          <serviceThrottling maxConcurrentCalls="100" maxConcurrentInstances="100" maxConcurrentSessions="100"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="defaultEndpointBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="ExcelUpload.UploadFile"  behaviorConfiguration="defaultServiceBehaviour">
        <endpoint address="" behaviorConfiguration="defaultEndpointBehaviour" bindingConfiguration="crossDomain" binding="webHttpBinding" contract="ExcelUpload.IUploadFile"></endpoint>
      </service>
    </services>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
        <add binding="basicHttpBinding" scheme="http"/>
    </protocolMapping>    
  </system.serviceModel>
  <system.webServer>
    <security>
      <authentication>
        <anonymousAuthentication enabled="true"/>
      </authentication>
      <requestFiltering allowHighBitCharacters="true">
        <verbs allowUnlisted="false">
          <add verb="POST" allowed="true"/>
          <add verb="GET" allowed="true"/>
        </verbs>
      </requestFiltering>
    </security>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

网络应用

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UploadTest.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Uploading using WCF REST API</title>
    <script type="text/javascript">

        function uploadBlobOrFile(blobOrFile) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://intranet-services.tosama.si/CroSalesExcelUpload/UploadFile.svc/UploadExcel/', true);

            xhr.setRequestHeader('Content-length', blobOrFile.size);

            xhr.onload = function (e) {
                progressBar.value = 0;
                progressBar.textContent = progressBar.value;
            };

            // Listen to the upload progress.
            var progressBar = document.querySelector('progress');
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    progressBar.value = (e.loaded / e.total) * 100;
                    progressBar.textContent = progressBar.value; // Fallback.
                }
            };
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            };

            xhr.send(blobOrFile);
        }

    </script>
</head>
<body>
    <input id="filePicker" type="file" name="Package" accept="image/*"/>
    <br />
    <progress min="0" max="100" value="0">0% complete</progress>
    <br />
    <button title="upload" 
            onclick="if (filePicker.files[0]) uploadBlobOrFile(filePicker.files[0])">
        <span>Upload</span>
    </button>
</body>
</html> 

1 个答案:

答案 0 :(得分:0)

非常基本的是,你为什么要为目录创建对象?

@&#34; C:\用户\公共\文件&#34;

尝试更改为@&#34; C:\ Users \ Public \ Documents \ MyFile.txt&#34;

在这里,您可以使用任何类型的文件而不是txt。 并且不要忘记为要上传的文件设置限制。

希望它有帮助..!