How to handle an Exception of an http Request in Asp Net MVC

Asked

Viewed 72 times

1

Hi, I have an app on ASP.net MVC who’s making a requisition http through a connection port that is available through a service, which is running on the server. The controller calls the method and sends the answer to the view.

When I drop this service and run the application, it generates the exceptions: httpRequestException, WebException and SocketException.

I’d like to know how to treat that exception taking a message to the user in a friendly way in my view, when for example we decide to maintain the server and the port is out of range.

I’ve tried the Try, but in the execution he ignores the block, it’s like I haven’t even put the try and catch there.

Method that makes the connection:

public static string BaseUrl
{
get
{
//Base da Api seguido pelo IP e Porta de conexão do servidor
return "http://IP:888/api/millenium!status_pedidov/pedido_venda/";
}
}

public static object GetApiResultadoPedido(string CodigoPedido)
{

//Metodo que faz requisicao a API do Millennium
string action = string.Format("listaporpedido?cod_pedidov={0}&$format=json", CodigoPedido);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseUrl + action);
//LINHA ONDE A EXCESSAO É GERADA:
HttpResponseMessage response = HttpInstance.GetHttpClientInstance().SendAsync(request).Result;
var JsonResponse = response.Content.ReadAsStringAsync().Result;
return JsonResponse;
}
  • I was able to sort it out after a while... Actually just put an if below the Try and send a Return in the null value so that in the controller you can do the validation and then return to the view a Tempdata with the error message.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.