POST To WCF Сервис - PullRequest
       1

POST To WCF Сервис

1 голос
/ 06 февраля 2011

Я пытаюсь отправить сериализованный объект в мою службу WCF.Тем не менее, я получаю сообщение об ошибке «NotFound».Я бился головой об этом в течение трех дней.Может кто-нибудь сказать мне, что я делаю не так?Ниже приведен мой код на стороне клиента, моя операция службы WCF и определение класса, которое я пытаюсь сериализовать.

Код на стороне клиента

// Build a wrapper exception that will be serialized
Exception ex = e.ExceptionObject;
MyException exception = new MyException(ex.Message, ex.StackTrace, "silverlight app", ex.GetType().FullName, string.Empty);

string json = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
  // Serialize the object 
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectType);
  serializer.WriteObject(memoryStream, objectToSerialize);

  // Convert the data to json
  byte[] bytes = memoryStream.ToArray();
  int count = (int)(memoryStream.Length);
  json = Encoding.UTF8.GetString(bytes, 0, count);
}

 // Submit the information to log
string url = "http://localhost:90/services/MyService.svc/LogError";
WebClient loggingService = new WebClient();
loggingService.UploadStringCompleted += new UploadStringCompletedEventHandler(loggingService_UploadStringCompleted);
loggingService.Headers["Content-type"] = "application/json";
loggingService.Encoding = Encoding.UTF8;
loggingService.UploadStringAsync(new Uri(logExceptionUrl), "POST", json);

MyException (версия на стороне клиента)

public class MyException : Exception
{
  private readonly string stackTrace;
  public override string StackTrace
  {
    get {
      return base.StackTrace;
    }
  }

  private readonly string message;
  public override string Message
  {
    get {
      return base.Message;
    }
  }

  private readonly string component;
  public string Component
  {
    get { return component; }
  }

  private readonly string typeName;
  public string TypeName
  {
    get { return typeName; }
  }

  private readonly string miscellaneous;
  public string Miscellaneous
  {
    get { return miscellaneous; }
  }

  public MyException()
  { }

  public MyException(string message) : base(message)
  { }

  public MyException(string message, Exception inner) : base(message, inner)
  { }

  public MyException(string message, string stackTrace) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
  }

  public MyException(string message, string stackTrace, string component, string typeName, string miscellaneous) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
    this.component = component;
    this.typeName = typeName;
    this.miscellaneous = miscellaneous;
  }
}

Служба WCF

[OperationContract]
[WebInvoke(UriTemplate = "/LogError", BodyStyle=WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string LogError(MyException exc)
{
  try
  { 
    // Write the details of exc to the database 
    return "ok";
  }
  catch (Exception ex)
  {
    return "error";
  }
}

MyException в проекте WCF

[Serializable]
public class MyException : Exception
{
  public override string StackTrace
  {
    get { return base.StackTrace; }
  }
  private readonly string stackTrace;

  public override string Message
  {
    get { return base.Message; }
  }
  private readonly string message;

  public string Component
  {
    get { return component; }
    set { /* */ }
  }
  private readonly string component;

  public string TypeName
  {
    get { return typeName; }
    set { /* */ }
  }
  private readonly string typeName;

  public string Miscellaneous
  {
    get { return miscellaneous; }
    set { /* */ }
  }
  private readonly string miscellaneous;

  public MyException() 
  {}

  public MyException(string message) : base(message)
  { }

  public MyException(string message, Exception inner) : base(message, inner)
  { }

  public MyException(string message, string stackTrace) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
  }

  public MyException(string message, string stackTrace, string component, string typeName, string miscellaneous) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
    this.component = component;
    this.typeName = typeName;
    this.miscellaneous = miscellaneous;
  }   

  protected MyException(SerializationInfo info, StreamingContext context) : base(info, context)
  {
    component = info.GetString("component");
    typeName = info.GetString("typeName");
    miscellaneous = info.GetString("miscellaneous");
  }

  public override void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    base.GetObjectData(info, context);
    info.AddValue("component", component);
    info.AddValue("typeName", typeName);
    info.AddValue("miscellaneous", miscellaneous);
  }
}

Спасибо за помощь!

1 Ответ

2 голосов
/ 06 февраля 2011

Чтобы вызвать веб-сервис в .NET, вы обычно генерируете клиентский прокси. Вы можете использовать утилиту svcutil.exe или Добавить ссылку на службу ... в Visual Studio. Получив строго типизированный клиентский прокси, вы просто вызываете службу, не используя никаких WebClients, MemoryStreams, DataContractJsonSerializers, ...

using (var client = new MyWebServiceClient())
{
    var result = client.SomeMethod();
}

Инфраструктура WCF позаботится обо всем остальном.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...