Uploading files WCF Web API Endpoint

a 夏天 提交于 2019-12-06 12:13:19

问题


Is there any way to upload a file to WCF web API endpoint? If so, how can I access Network Stream to read data?

Any help is very much appreciated.

Thanks.


回答1:


Assuming you are talking about on the client side:

One way to do it is to create a FileContent class that derives from HttpContent. In the overrides you will be given the NetworkStream when the HTTPClient is ready to receive the stream.

If you are asking about the server side, then you can simply get hold of the HTTPRequestMessage and access the httpRequestMessage.Content.ContentReadStream property.


Update

By default the WCF Transport is limited to sending messages at 65K. If you want to send larger you need to enable "Streaming Transfer Mode" and you need to increase the size of MaxReceivedMessageSize, which is there just as a guard to prevent someone killing your server by uploading a massive file.

So, you can do this using binding configuration or you can do it in code. Here is one way to do it in code:

var endpoint = ((HttpEndpoint)host.Description.Endpoints[0]);  //Assuming one endpoint
endpoint.TransferMode = TransferMode.Streamed;
endpoint.MaxReceivedMessageSize = 1024 * 1024 * 10;  // Allow files up to 10MB



回答2:


This answer is only designed to add some details with Web API preview 6.

TransferMode and MaxRecievedMessageSize are new exposed through the WebApiConfigurationClass.

var builder = new WebApiConfiguration();
builder.TransferMode = TransferMode.Streamed;
builder.MaxReceivedMessageSize = 1024 * 1024 * 10;

var serviceRoute = new WebApiRoute(route, new WebAPIServiceHostFactory() { Configuration = builder }, typeof(MyService));

I like it!



来源:https://stackoverflow.com/questions/6177118/uploading-files-wcf-web-api-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!