简体   繁体   English

在自托管Web服务器环境中通过POST REST API上传C#文件

[英]C# File Upload via POST REST API in a Self-Hosted Web Server Environment

I have a Web Service I've created that is self-hosted using "HttpSelfHostConfiguration" from "System.Web.Http.SelfHost". 我有一个已创建的Web服务,该服务使用“ System.Web.Http.SelfHost”中的“ HttpSelfHostConfiguration”进行自我托管。 I need to create a REST API that allows others to make a POST call to upload a file to my service. 我需要创建一个REST API,允许其他人进行POST调用以将文件上传到我的服务。

All of the research I've done so far has been for hosted Web Services, like in IIS. 到目前为止,我所做的所有研究都是针对托管Web服务的,例如IIS。 So what that allows them to do is use "HttpContext.Current" to get the HttpRequest content. 因此,允许他们执行的操作是使用“ HttpContext.Current”获取HttpRequest内容。

However, in self-hosted environments, "HttpContext.Current" is null, so I need to go an alternate route. 但是,在自托管环境中,“ HttpContext.Current”为null,因此我需要走一条替代路线。 My Google-fu may be off, but I can't seem to find any information with how to accomplish this in a self-hosted environment. 我的Google-fu可能已关闭,但我似乎找不到任何有关如何在自托管环境中完成此操作的信息。

Does anyone have any examples or advice on how to accomplish creating a REST API that allows people to POST files to in this situation? 在这种情况下,是否有人对如何完成创建REST API(允许人们发布文件)有任何示例或建议?

Thanks in advance! 提前致谢!

Use HttpRequestMessage like below in your post method 在您的post方法中使用如下所示的HttpRequestMessage

 public HttpResponseMessage Post(HttpRequestMessage request) {...} 

Then you can use some thing like below to extract the context of the request message 然后,您可以使用如下所示的方法来提取请求消息的上下文

string sRequestcXMLContent = Encoding.UTF8.GetString(request.Content.ReadAsByteArrayAsync().Result); 字符串sRequestcXMLContent = Encoding.UTF8.GetString(request.Content.ReadAsByteArrayAsync()。Result);

Hope this will help you! 希望这个能对您有所帮助!

this post helped me allot but i thought i'd post my solution to help people. 这篇文章帮助我分配,但我认为我会发布我的解决方案来帮助人们。

    public async void Post(HttpRequestMessage Message)
    {
        MultipartMemoryStreamProvider x = await Message.Content.ReadAsMultipartAsync();
        Byte[] xx = await x.Contents[0].ReadAsByteArrayAsync();
        File.WriteAllBytes("c:\\test.png", xx);
    }

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

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