gpt4 book ai didi

wcf - 如何将WCF异常传达给WebClient

转载 作者:行者123 更新时间:2023-12-02 04:04:43 24 4
gpt4 key购买 nike

我有一个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);
}

我不断收到异常消息: "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),则WebException的Response属性将具有主体,您可以在该主体中读取客户端。

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

关于wcf - 如何将WCF异常传达给WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com