質問

無効なデータが送信されたときに例外をスローするWCF Webサービスがあります。データは、WebClientオブジェクトを使用してHTTP投稿を介して送信されます。

これが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);
           }

私はメッセージで例外を取得し続けます: "The remote server returned an error: (500) Internal Server Error"client.UploadValues(this.Address, data);.

より詳細な情報がに返されることを確認する方法はありますか WebClient?

また、これらの例外(WCFサービス)がEventLogにログに記録されることを確認するにはどうすればよいですか? (基本的に、何が起こったのかを知る必要があります)。

役に立ちましたか?

解決

を見てみましょう HttpResponseException (名前空間 Microsoft.ApplicationServer.Http.Dispatcher) - エラーケースの応答を制御できる方法です。ステータスコードを指定でき、 HttpResponseMessage, 、メッセージ本文を制御できます。

クライアント側では、電話するとき WebClient.UploadValues, 、その呼び出しを包み、キャッチします WebException. 。サービスが非成功したステータスコード(例えば500、400)で応答を返す場合、 Response WebExceptionのプロパティには、クライアントで読むことができるボディがあります。

別のオプションは使用することです HttpClient の代わりに WebClient, 、その場合、あなたは単に HttpResponseMessage 直接。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top