jchensor
jchensor

Reputation: 107

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". I need to create a REST API that allows others to make a POST call to upload a file to my service.

All of the research I've done so far has been for hosted Web Services, like in IIS. So what that allows them to do is use "HttpContext.Current" to get the HttpRequest content.

However, in self-hosted environments, "HttpContext.Current" is null, so I need to go an alternate route. 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.

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?

Thanks in advance!

Upvotes: 1

Views: 2332

Answers (2)

Christophe
Christophe

Reputation: 87

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);
    }

Upvotes: 1

Darshana
Darshana

Reputation: 604

Use HttpRequestMessage like below in your post method

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);

Hope this will help you!

Upvotes: 1

Related Questions