【问题标题】:Can't get WebClient.UploadFile from C# Rest service无法从 C# Rest 服务获取 WebClient.UploadFile
【发布时间】:2021-02-06 07:21:08
【问题描述】:

我目前正在尝试将一些 aspx 页面迁移到 C# Rest 服务中。 我不能改变调用者,只能改变被调用的服务。

我是这样称呼的:

var myWebClient = new WebClient();
// here I'm dealing with cookie but not sure it is worth explaining how I pass it cause it isn't the problem
var response = myWebClient.UploadFile(sURL, fileFulName); // fileFulName is the path of my local file

在 aspx 中,文件可以这样获取:

HttpPostedFile file = Request.Files[0];

首先我尝试了同样的代码:

var file = HttpContext.Current.Request.Files[0];

这会引发我可以通过将其添加到 web.config(appSettings 部分)来管理的异常:

<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />

但是现在,它没有抛出异常,而是一个空数组。 这是我的端点方法:

[OperationContract]
 [WebInvoke(
        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "/upload?myParam={myGetParam}]
void Upload(Stream fileStream, string myGetParam);

我不知道如何让它工作。我尝试使用字节数组作为输入,但响应是 400 Bad Request。然后我尝试查看 fileStream 中的内容,但它不包含我的文件,只有几个字符。

我不知道如何获取上传的文件。

【问题讨论】:

    标签: c# rest wcf upload


    【解决方案1】:

    以下是创建可将文件上传到 .NET 核心 REST API 服务的路由的方法:

    [HttpPost]
    [Route("api/upload")]
    public async Task<IActionResult> Post(List<IFormFile> files)
    {
        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                using (var reader = new StreamReader(formFile.OpenReadStream()))
                {
                     // do something with the file content.
                }
            }
        }
    
        return Ok();
    }
    

    【讨论】:

    • 感谢您的回答。遗憾的是,由于组策略,我无法访问 Microsoft.AspNetCore。我看一个不使用它的解决方案。目前我在我的接口中使用 System.ServiceModel 命名空间。
    【解决方案2】:

    你可以查看我的上传文件功能的代码:

    public void UploadFile(string fileName, Stream fileContents)
    
            {
    
                byte[] buffer = new byte[10000];
    
                int bytesRead, totalBytesRead = 0;
    
                do
    
                {
    
                    bytesRead = fileContents.Read(buffer, 0, buffer.Length);
    
                    totalBytesRead += bytesRead;
    
                } while (bytesRead > 0);
    
                Console.WriteLine("Service: Received file {0} with {1} bytes", fileName, totalBytesRead);
    
            }
    
     
    
    The service contract:
    
     
    
       [ServiceContract] 
    
        public interface IReceiveData 
    
        { 
    
            [WebInvoke(UriTemplate = "UploadFile/{fileName}")] 
    
            void UploadFile(string fileName, Stream fileContents); 
    
        }
    
    The main function:
    
     
    
    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(); 
    
                Console.WriteLine("Host opened"); 
    
      
    
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "/UploadFile/Test.txt"); 
    
                req.Method = "POST"; 
    
                req.ContentType = "text/plain"; 
    
                Stream reqStream = req.GetRequestStream(); 
    
                byte[] fileToSend = new byte[12345]; 
    
                for (int i = 0; i < fileToSend.Length; i++) 
    
                { 
    
                    fileToSend[i] = (byte)('a' + (i % 26)); 
    
                } 
    
                reqStream.Write(fileToSend, 0, fileToSend.Length); 
    
                reqStream.Close(); 
    
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
    
                Console.WriteLine("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); 
    
                host.Close(); 
    
      
    
            } 
    

    结果如下:

    更多信息可以参考这个链接:

    https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/create-a-service-arbitrary-data-using-wcf

    【讨论】:

    • 谢谢,但是这段代码的问题是我不能改变调用,只能改变被调用的服务。通过我提供的调用,我收到的 Stream 不包含该文件。当我上传了一个超过 1 ko 的文件时,大小为 42 字节。
    • 你目前只有WCF客户端,想上传文件到服务器吗?
    • 我的客户端是 C# 客户端(不是 WCF)。呼叫电话是我在我的问题上添加的电话。问题是我不能对客户电话做任何改变。这些调用以前在 aspx 中被截获并且工作正常,所以我知道调用代码并不是完全错误的,即使最初并不是要调用 REST 服务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多