Search code examples
asp.netwcfwcf-binding

How do I get details of WCF bindings programatically


I've written an ASP.Net web site with a WCF backend. One of the features of the web site is that it allows the user to download a file that is streamed from the WCF service.

The web.config file in the ASP.Net project has a maximum file size set in the binding (maxBufferSize and maxReceivedMessageSize). To stop users downloading files that exceed this size, I need to check the file size against the maximum file size in the web.config file, how do I go about this?

I've found out about the binding.CreateBindingElements() but I'm unsure how to get the instance of the binding in the first place.

EDIT: Binding details are as follows:

<binding name="BasicHttpBinding_IC_Server" closeTimeout="00:01:00"
      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
      messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
      useDefaultWebProxy="true">

EDIT: The WCF service has a method that returns the file as a stream. An ASP.Net web page gets the file, stores it in a memory stream and then returns it as a byte array to the user.

If the file size is too small, I get this error:

The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.

Upping the buffer size fixes it, but I'd rather avoid this error by comparing the file size against the maxBufferSize.


Solution

  • Finally managed to work it out myself.

    Where sr is the service reference:

    System.ServiceModel.Description.ServiceEndpoint endpoint = sr.Endpoint;
    System.ServiceModel.Channels.BindingElementCollection elements =
        Endpoint.Binding.CreateBindingElements();
    long size = elements.Find<System.ServiceModel.Channels.TransportBindingElement>().MaxReceivedMessageSize;