Pregunta

Tengo un servicio web de WCF que arroja excepciones cuando se envían datos no válidos. Los datos se envían a través de una publicación HTTP utilizando el objeto WebClient.

Aquí está el código para el servicio web:

[WebInvoke(UriTemplate = "update", Method = "POST")]
public JsonValue Update(HttpRequestMessage message)
{
    var context = new Entities();
    dynamic response = new JsonObject();

    // in order to retrieve the submitted data easily, reference the data as a dynamic object
    dynamic data = message.Content.ReadAs(typeof(JsonObject), new[] { new FormUrlEncodedMediaTypeFormatter() });

    // retrieve the submitted data
    int requestId = data.requestId;
    int statusId = data.statusId;
    string user = data.user;
    string encryptedToken = data.token;
    string notes = data.notes;

    // retrieve the request with a matching Id
    var request = context.Requests.Find(requestId);

    // make sure the request exists
    if (request == null)
        throw new FaultException("The supplied requestId does not exist.");

    // make sure the submitted encrypted token is valid
    var token = DecryptToken(encryptedToken);
    if (token == null)
        throw new FaultException("Invalid security token.");

    // TODO: Validate other token properties (e.g. email)?
    if (!request.User.UserName.Equals(token.UserName))
        throw new FaultException("Invalid security token.");

    // additional logic removed ...
}

Y aquí está el código que envía datos al servicio web:

            // use the WebClient object to submit data to the WCF web service
            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;

                // the data will be submitted in the format of a form submission
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                var data = new NameValueCollection();

                // prepare the data to be submitted
                data.Add("requestId", requestId.ToString());
                data.Add("statusId", this.StatusId);
                data.Add("token", token.ToString());
                data.Add("user", this.User);
                data.Add("notes", this.Notes);

                // submit the data to the web service
                var response = client.UploadValues(this.Address, data);
           }

Sigo recibiendo una excepción con el mensaje: "The remote server returned an error: (500) Internal Server Error" a client.UploadValues(this.Address, data);.

¿Hay alguna manera de asegurarme de que se devuelva información más detallada al WebClient?

Además, ¿cómo puedo asegurarme de que estas excepciones (en el servicio WCF) se registren en EventLog? (Básicamente solo necesito saber qué pasó).

¿Fue útil?

Solución

Echa un vistazo a HttpResponseException (espacio de nombres Microsoft.ApplicationServer.Http.Dispatcher) - Son la forma en que puede controlar la respuesta para los casos de error. Puede especificar el código de estado y tiene control sobre el HttpResponseMessage, en el que puedes controlar el cuerpo del mensaje.

En el lado del cliente, cuando llamas WebClient.UploadValues, envuelva esa llamada y atrapa un WebException. Si el servicio devuelve una respuesta con un código de estado no exitoso (por ejemplo, 500, 400), el Response La propiedad de WebException tendrá el cuerpo, en el que puede leer en su cliente.

Otra opción es usar HttpClient en vez de WebClient, en cuyo caso simplemente puedes mirar el HttpResponseMessage directamente.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top