gpt4 book ai didi

c# - 在网络浏览器上显示自定义错误消息

转载 作者:行者123 更新时间:2023-12-03 09:09:21 26 4
gpt4 key购买 nike

我创建了一个ASP.NET Web API,该API调用Java Web服务器来检索数据。当Java Web服务器关闭时,我希望Web API显示错误消息:{"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;
}

}

AdditionController.cs
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);
}
}

有人请帮助我,非常感谢。

最佳答案

如果捕获到Exception类型的异常,然后确定调用的服务器已关闭,那将不是真的。在调用另一个服务之前或在另一个服务成功返回之后,您自己的代码中可能会出现问题。因此,您需要谨慎做出决定。

话虽如此,仍然很难说何时可以自信地做出决定:主叫服务是否返回正确的消息等。

无论如何,您可以执行以下操作:

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

关于c# - 在网络浏览器上显示自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707320/

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