如何在 WCF REST C# 中进行异常处理
How doing the exception handling in WCF REST C#
我有一个 Wcf Rest 服务
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
void Import(stringrequest);
我的试用代码:
public void Import(string request)
{
if (request != null)
{
//....
}
else
{
throw new ApplicationException("Empty DATA");
}
}
事实上,当我在 POSTMAN 中测试我的 wcf 服务时,如果我输入一个空字符串 ---> 我要显示的对象 "Empty DATA",我想显示关于 else 处理的特定错误消息,
怎么做到的?谢谢,
如果你想处理异常,你应该使用try-catch。
当你想处理所有可能的行为,比如空字符串或充满数字的字符串等。你可以使用if-else 陈述你正在做的。
您需要将 return 类型从 void
更改为 string
:
public string Import(string request) {
if (String.IsNullOrEmpty(request)) {
// ...
return "{ \"Status\" : \"Ok\" }"; // or null if you don't want to return anything
}
else
{
return "{ \"Status\" : \"Error : Empty DATA\" }";
}
}
您还可以查看此 link 以了解有关如何在 C# 中使用 Json 的更多信息。
and how to return Json,这可以帮助您更多地了解 WCF REST 的工作原理。
希望这对您有所帮助。
我有一个 Wcf Rest 服务
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
void Import(stringrequest);
我的试用代码:
public void Import(string request)
{
if (request != null)
{
//....
}
else
{
throw new ApplicationException("Empty DATA");
}
}
事实上,当我在 POSTMAN 中测试我的 wcf 服务时,如果我输入一个空字符串 ---> 我要显示的对象 "Empty DATA",我想显示关于 else 处理的特定错误消息,
怎么做到的?谢谢,
如果你想处理异常,你应该使用try-catch。
当你想处理所有可能的行为,比如空字符串或充满数字的字符串等。你可以使用if-else 陈述你正在做的。
您需要将 return 类型从 void
更改为 string
:
public string Import(string request) {
if (String.IsNullOrEmpty(request)) {
// ...
return "{ \"Status\" : \"Ok\" }"; // or null if you don't want to return anything
}
else
{
return "{ \"Status\" : \"Error : Empty DATA\" }";
}
}
您还可以查看此 link 以了解有关如何在 C# 中使用 Json 的更多信息。 and how to return Json,这可以帮助您更多地了解 WCF REST 的工作原理。
希望这对您有所帮助。