Search code examples
c#wcfgenerics

How to pass any type of object as input parameter with only 1 method


I've a WCF service with one method which will be called from multiple web API controllers like in the below code.

    public string Print(PdfPrinterRequest _request)
    {
        PdfPrinterService.PdfPrinterClient _Client = new PdfPrinterService.PdfPrinterClient();
        PdfPrinterResponse _response = new PdfPrinterResponse();
        return _Client.Print(_request.Document, out _pdfResponse);
    }

PdfPrinterRequest(Document class) is the entity which I'm passing to get the response message from WCF service.Currently the document class holds few properties(REquest Header). I would like to call the same Print method from other API and pass type 'Customer' to WCF service. How can i achieve this? Can anyone please suggest me the correct implementation?

Below is my WCF service code,

   public class PdfPrinterService : IPdfPrinter
   {
      public PdfPrinterResponse Print(PdfPrinterRequest request)
      {
        return PdfPrinterFacade.PrintPdf(request);
      }
   }

   public static PdfPrinterResponse PrintPdf(PdfPrinterRequest request)
    {
        PdfPrinterResponse response = new PdfPrinterResponse();
        //Process the request and send back the response message
    }

    [MessageContract]
    public class PdfPrinterRequest
    {
    private Document _document;

    [MessageBodyMember]
    public Document Document
    {
        get { return _document; }
        set { _document = value; }
    }
   }

How to pass a dynamic class object as a parameter in place of PdfPrinterRequest which is no bound to only one type(Document)? Please suggest.

Thanks,


Solution

  • Warning: The NetDataContractSerializer poses a significant security risk and should be avoided.


    If this service does not need to be interoperable, you can switch to NetDataContractSerializer, which uses full .NET type information, and is able to serialize many more types (but not any type - that's impossible). Grab the UseNetDataContractSerializerAttribute from this answer and apply like so:

    [UseNetDataContractSerializer]
    public class PdfPrinterService : IPdfPrinter
    {
       public PdfPrinterResponse Print(PdfPrinterRequest request)
       {
         return PdfPrinterFacade.PrintPdf(request);
       }
    }
    
    [MessageContract]
    public class PdfPrinterRequest
    {
        [MessageBodyMember]
        public object Document { get; set; }
    }