C# 在web浏览器上显示自定义错误消息
我创建了一个ASP.NETWebAPI,它调用JavaWeb服务器来检索数据。当java web服务器关闭时,我希望web API显示一条错误消息:C# 在web浏览器上显示自定义错误消息,c#,asp.net,error-handling,C#,Asp.net,Error Handling,我创建了一个ASP.NETWebAPI,它调用JavaWeb服务器来检索数据。当java web服务器关闭时,我希望web API显示一条错误消息:{“ErrorMessage:“server is down}我应该添加哪些代码来实现浏览器上显示的自定义错误消息 这是我的密码: RestfulClient.cs public class RestfulClient { private static HttpClient client; private static string
{“ErrorMessage:“server is down}
我应该添加哪些代码来实现浏览器上显示的自定义错误消息
这是我的密码:
RestfulClient.cs
public class RestfulClient
{
private static HttpClient client;
private static string BASE_URL = "http://localhost:8080/";
static RestfulClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> addition(int firstNumber, int secondNumber)
{
try
{
var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
//What do i have to code here?
}
return null;
}
}
public class Temp
{
public string firstNumber { get; set; }
public string secondNumber { get; set; }
public string sum { get; set; }
}
public class AdditionController : ApiController
{
private RestfulClient restfulClient = new RestfulClient();
public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
{
var result = await restfulClient.addition(firstNumber, secondNumber);
var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
return Json(resultDTO);
}
}
公共类RestfulClient
{
私有静态HttpClient;
私有静态字符串BASE_URL=”http://localhost:8080/";
静态RestfulClient()
{
client=新的HttpClient();
client.BaseAddress=新Uri(基本URL);
client.DefaultRequestHeaders.Accept.Add(
新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
}
公共异步任务添加(int firstNumber,int secondNumber)
{
尝试
{
var endpoint=string.Format(“addition/{0}/{1}”,firstNumber,secondNumber);
var response=await client.GetAsync(端点);
return wait response.Content.ReadAsStringAsync();
}
捕获(例外e)
{
//我必须在这里编码什么?
}
返回null;
}
}
AdditionController.cs
public class RestfulClient
{
private static HttpClient client;
private static string BASE_URL = "http://localhost:8080/";
static RestfulClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> addition(int firstNumber, int secondNumber)
{
try
{
var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
//What do i have to code here?
}
return null;
}
}
public class Temp
{
public string firstNumber { get; set; }
public string secondNumber { get; set; }
public string sum { get; set; }
}
public class AdditionController : ApiController
{
private RestfulClient restfulClient = new RestfulClient();
public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
{
var result = await restfulClient.addition(firstNumber, secondNumber);
var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
return Json(resultDTO);
}
}
公共类临时
{
公共字符串firstNumber{get;set;}
公共字符串secondNumber{get;set;}
公共字符串和{get;set;}
}
公共类附加控制器:ApiController
{
private RestfulClient RestfulClient=new RestfulClient();
公共异步任务Get(int firstNumber,int secondNumber)
{
var result=await restfulClient.addition(firstNumber,secondNumber);
var resultDTO=JsonConvert.DeserializeObject(结果);
返回Json(resultDTO);
}
}
有人请帮帮我,非常感谢。如果您捕获到类型为
异常的异常,然后确定您调用的服务器已关闭,那将是不正确的。在调用其他服务之前或在其他服务成功返回之后,您自己的代码可能会出错。因此,你需要谨慎地做出决定
话虽如此,现在仍然很难说你什么时候可以自信地做出决定:呼叫服务是否返回正确的消息等
无论如何,你可以做类似的事情:
try
{
// ...
}
catch (System.Net.WebException ex)
{
if (ex.Status == System.Net.WebExceptionStatus.ConnectFailure)
{
// To use these 2 commented out returns, you need to change
// your method's return type to Task<IHttpActionResult>
// return Content(System.Net.HttpStatusCode.ServiceUnavailable, "Unavilable.");
// return StatusCode(System.Net.HttpStatusCode.ServiceUnavailable);
return "Unavailable"
}
}
catch(Exception ex)
{
// You could be here because something went wrong in your server,
// or the server you called which was not caught by the catch above
// because it was not WebException. Make sure to give it some
// thought.
// You need to change
// your method's return type to Task<IHttpActionResult> or
// just return a string.
return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}
试试看
{
// ...
}
捕获(System.Net.WebException-ex)
{
if(ex.Status==System.Net.WebExceptionStatus.ConnectFailure)
{
//要使用这两个注释掉的返回,您需要更改
//方法的返回类型为Task
//返回内容(System.Net.HttpStatusCode.ServiceUnavailable,“不可用”);
//返回状态码(System.Net.HttpStatusCode.ServiceUnavailable);
返回“不可用”
}
}
捕获(例外情况除外)
{
//你可能是因为你的服务器出了问题,
//或者您调用的服务器未被上述捕获捕获
//因为它不是WebException。一定要给它一些
//思想。
//你需要改变
//方法的返回类型为任务或
//只需返回一个字符串。
返回状态码(System.Net.HttpStatusCode.InternalServerError);
}
Atry/catch
…如果我将方法更改为Task,我可以返回Ok(响应)对吗?我应该将var endpoint
部分更改为什么?我想我需要它是Task,作为var endpoint=string.Format(“addition/{0}/{1}”,firstNumber,secondNumber)代码>当我从java web服务检索数据时,这一行代码很重要。为什么会有这么多“返回”对不起,请一定要指导我,我是个新手this@SushaNaidu您不需要将var端点
更改为任何内容。有很多回报,因为我想告诉你,你有这些选择。就用其中一个吧。您做了正确的事情,将其更改为Task
。如果您需要更多帮助,请告诉我。当我将其更改为Task
时,会出现两个错误。我在wait response.Content.ReadAsStringAsync()
下看到一条红线,错误状态无法将类型字符串隐式转换为System.Web.Http.IHttpActionResult