如何将 WCF 异常传递给 WebClient

发布于 2024-12-18 19:55:28 字数 2523 浏览 1 评论 0原文

我有一个 WCF Web 服务,在提交无效数据时会引发异常。数据使用 WebClient 对象通过 HTTP Post 提交。

这是 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 ...
}

这是向 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);
           }

我不断收到异常消息:“远程服务器返回错误:(500) 内部服务器错误”位于client.UploadValues(this.Address, data);

有没有办法确保将更详细的信息返回到 WebClient

另外,如何确保这些异常(在 WCF 服务中)记录到 EventLog 中? (基本上我只需要知道发生了什么)。

I have a WCF web service which throws exceptions when invalid data is submitted. The data is submitted via an HTTP Post using the WebClient object.

Here is the code for the web service:

[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 ...
}

And here is the code that submits data to the web service:

            // 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);
           }

I keep getting an exception with message: "The remote server returned an error: (500) Internal Server Error" at client.UploadValues(this.Address, data);.

Is there a way I can make sure that more detailed information is returned to the WebClient?

Also, how can I make sure that these exceptions (in the WCF service) are logged to the EventLog? (Basically I just need to know what happened).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘东忘西忘不掉你 2024-12-25 19:55:28

看一下HttpResponseException(命名空间Microsoft.ApplicationServer.Http.Dispatcher) - 它们是您可以控制错误情况响应的方式。您可以指定状态代码,并且可以控制 HttpResponseMessage,在其中可以控制消息正文。

在客户端,当您调用 WebClient.UploadValues 时,包装该调用并捕获 WebException。如果服务返回带有不成功状态代码(例如 500、400)的响应,则 WebException 的 Response 属性将包含正文,您可以在客户端中读取该正文。

另一种选择是使用 HttpClient 而不是 WebClient,在这种情况下,您可以直接查看 HttpResponseMessage

Take a look at HttpResponseException (namespace Microsoft.ApplicationServer.Http.Dispatcher) - they're the way where you can control the response for error cases. You can specify the status code, and you have control over the HttpResponseMessage, in which you can control the message body.

On the client side, when you call WebClient.UploadValues, wrap that call and catch a WebException. If the service returns a response with a non-successful status code (e.g., 500, 400), the Response property of the WebException will have the body, in which you can read in your client.

Another option is to use HttpClient instead of the WebClient, in which case you can simply look at the HttpResponseMessage directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文