0

I have an ASP.NET Web API, which calls a java web service. When I run the ASP.NET Web API, I will get a JSON string as an output. Right now, I want to do error handling where when the java web service is down and when I run the API, I want it to show output as {"Error": Java web service is down} (In JSON) instead of a whole chunk of error message which the user will not understand.

Here are my codes:

RestfulClient.cs (model class)

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ApiClientJavaWebService.Models
{
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 code here?
        }
        return null;
    }
  }
} 

AdditionController.cs (controller class)

using ApiClientJavaWebService.Models;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Web.Http;

namespace ApiClientJavaWebService.Controllers
{
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);
    }
  }
}

WebApiConfig.cs

using System;
using System.Web.Http;

namespace ApiClientJavaWebService
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "AdditionApi",
            routeTemplate: "api/serveraddition/{firstNumber}/{secondNumber}",
            defaults: new { action = "Get", controller = "Addition" }
        );

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", "text/html",
            StringComparison.InvariantCultureIgnoreCase, true, "application/json")
        );
    }
  }
}

Someone please do help me. Thank you so much.

Susha Naidu
  • 307
  • 1
  • 3
  • 16

1 Answers1

0

You will need to include using System.Web.Script.Serialization.

public async Task<JsonResult> addition(int firstNumber, int secondNumber)
       {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            var result=await response.Content.ReadAsStringAsync();
            return new (JavaScriptSerializer().Serialize(new { Result = result});
        }

        catch (Exception e)            
        {
          return new (JavaScriptSerializer().Serialize(new { status = 
         "error", message = "Server is not running" });
        }

   } 
sifa vahora
  • 117
  • 11
  • Hi, thank u for answering. If i change `String` to `ActionResult`, i get error at other parts of my codes. under `await response.Content.ReadAsStringAsync();` i get a red line and the error message states `Cannot implicitly convert type String to `System.Web.Mvc.Actionresult`. – Susha Naidu Dec 05 '17 at 08:22
  • Is there any other way to achieve what i want? – Susha Naidu Dec 05 '17 at 08:24
  • you simply want to display the string right ? in that case you change that line to `return Content (await response.Content.ReadAsStringAsync());` – sifa vahora Dec 05 '17 at 08:24
  • I get error message: `Non-invocable member Content cannot be used like a method` – Susha Naidu Dec 05 '17 at 08:58
  • Thank u, but i am still getting errors :( The error states: `Predefined type System.ValueTuple2 is not defined or imported` and `new cannot be used with tuple type. Use a tuple literal expression instead` – Susha Naidu Dec 06 '17 at 02:49
  • can you please post the entire class with all the using statements. also is your class a controller class or where does it reside in your solution ? – sifa vahora Dec 06 '17 at 04:56
  • I have included all the classes – Susha Naidu Dec 06 '17 at 09:05
  • https://stackoverflow.com/questions/38382971/predefined-type-system-valuetuple%C2%B42%C2%B4-is-not-defined-or-imported try this .rest everything seems fine – sifa vahora Dec 07 '17 at 13:48