【问题标题】:Posting any type of request object as parameter to the Web API将任何类型的请求对象作为参数发布到 Web API
【发布时间】:2016-08-19 08:16:39
【问题描述】:

我有一个 Web API,它将类对象作为输入参数并将其发布到 WCF 服务操作合同。 WCF 服务被设计成它接受任何类型的请求,并对已经到来的请求类型和需要执行的代码进行内部映射。其逻辑如下。

    public class PdfPrinterService : IPdfPrinter
    {
    public PdfPrinterResponse Print(PdfPrinterRequestBase request)
    {
        if (request is Request1)
        {
           //Process user report request and send back the response
        }
        if (request is Request2)
        {
          //Process request 2 and send back the response
        }
       return PdfPrinterFacade.PrintPdf();
    }
 }

  //IPdfPrinter
  public interface IPdfPrinter
   {
    [OperationContract]
    PdfPrinterResponse Print(PdfPrinterRequestBase request);
   }

  //PdfPrinterRequestBase
  [DataContract]
  [KnownType(typeof(Request1))]
  [KnownType(typeof(Request2))]
  public class PdfPrinterRequestBase : IRequest
  {
     [DataMember]
     public RequestHeader ReqHdr { get; set; }
  }

 //Web API Request1
  public PdfPrinterResponse Print(Request1 _request1)
    {
        PdfPrinterService.PdfPrinterClient 
        _Client = new PdfPrinterService.PdfPrinterClient();
        return _Client.Print(_request1);
    }

   //Web API Request2
    public PdfPrinterResponse Print(Request2 _request2)
    {
        PdfPrinterService.PdfPrinterClient _Client = 
        new PdfPrinterService.PdfPrinterClient();
        return _Client.Print(_request2);
     }

上述方法对我来说没问题,但计划只有 1 个 API 接受任何类型的对象并将其传递给 WCF 服务和我所做的映射(如果请求 1,则处理并发送回响应,否则如果请求2 个进程和发回等)应与 1 个 API 调用一起使用。非常感谢您为实现这一目标提供的任何帮助。

【问题讨论】:

  • 您可以将原始 JSON 获取到您的 Print 方法中,然后尝试首先将其反序列化为 Request1,如果失败则返回 Request2
  • @Michael :听起来不错,但是 UI 会向我发送一个包含 3 或 4 个对象的对象。我不知道我需要了解在 WCF 中处理它的请求类型。任何示例插图都会对我有所帮助。谢谢!
  • 你看过Mediatr吗? github.com/jbogard/MediatR

标签: c# wcf oop design-patterns asp.net-web-api


【解决方案1】:

也许这行得通?

伪代码

[HttpPost]
public PdfPrinterResponse Print()
{
   var json = Request.Content.ReadAsByteArrayAsync().Result;

   Requeste1 request1;
   if(TrySerialzieTo<Request1>(json, out request1))
       // send request to wcf service

   Requeste2 request2;
   if(TrySerializeTo<Request2>(json, out requeste2))
       // send request to wcf service

}

private bool TrySerializeTo<T>(string json, out T request)
{
     // use JsonConvert.Deserialize<T>(json);
     throw new NotImplementedException();
}

【讨论】:

    猜你喜欢
    • 2020-04-25
    • 2018-03-09
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多