0

I have created a java web service that does addition function. I also have created an ASP.NET Web API which calls the java web service and displays the result. Lets say i typed in http://localhost:8080/addition/9/6 as the URL with input parameters that the java web service function should add. I get the output data as {"firstNumber":9,"secondNumber":6,"sum":15}. When i run my ASP.NET Web API, i will be redirected to http://localhost:55223/ and i will get the output data as {"firstNumber":9,"secondNumber":6,"sum":15}.

Right now, what i want to do is, when i run my ASP.NET Web API, i should be able to input parameters in the URL of the ASP.NET Web API (http://localhost:55223/addition/9/6) and instead of displaying result straight from Java web service, i want to use the function of the java web service in my API to calculate the sum of the input parameters. Does anyone have an idea on how can i go about doing that? What are the changes that i should make in my codes?

Here are my codes:

ASP.NET Web API codes

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)
        {
            HttpContext.Current.Server.Transfer("ErrorPage.html");
        }
        return null;
    }
}

ApiController.cs

public class ApiController : Controller
{
    private RestfulClient restfulClient = new RestfulClient();

    public async Task<ActionResult> Index()
    {
        int firstNumber = 9;
        int secondNumber = 6;
        var result = await restfulClient.addition(firstNumber, secondNumber);
        return Content(result);
    }
}

Java web service codes

AdditionController.java

@RestController
public class AdditionController {

private static final String template = " %s";
private static int getSum;

@RequestMapping("/addition/{param1}/{param2}")
@ResponseBody 

public Addition addition 
            (@PathVariable("param1") int firstNumber,@PathVariable("param2") int secondNumber) {
return new Addition(
        (String.format(template, firstNumber)), String.format(template, secondNumber));
  }
}   

Someone please help me thank you so much in advance.

Nidhi257
  • 754
  • 1
  • 5
  • 23
Susmitha Naidu
  • 109
  • 1
  • 12
  • What exactly is the issue and question? If you want to call the java service from web api, you are already doing that. – CodingYoshi Oct 30 '17 at 03:41
  • I want to be able to input parameters in the URL when i run the ASP.NET Web API – Susmitha Naidu Oct 30 '17 at 03:42
  • Then i want the ASP.NET Web API to display the sum of the two numbers like ` {"firstNumber":1,"secondNumber":1,"sum":2}`. The addition should be done using the function created by the java web service not by any new method created in the API itself – Susmitha Naidu Oct 30 '17 at 03:43

1 Answers1

1

what i want to do is, when i run my ASP.NET Web API, i should be able to input parameters in the URL of the ASP.NET Web API (http://localhost:55223/addition/9/6)

Web API uses many conventions and if you play nicely then things work pretty well. The first thing you need to do is to rename your controller like this:

public class AdditionController : ApiController
{
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    { 
        var result = await restfulClient.addition(firstNumber, secondNumber);
        return Ok(result);
    }
}

You will notice a few things in above code:

  1. The controller is called AdditionController. When you type addition in the url, the routing engine will look for a controller named Addition + the word Controller.
  2. It inherits ApiController not Controller.
  3. It has a Get action. If you make a GET request, the API routing engine will search for an action named Get or starting with Get. Thus it will find this action.
  4. The action is returning IHttpActionResult. See my answer here for why.
  5. It uses the extension method named Ok to return an HTTP Status code of 200. This is to follow good restful guidelines and HTTP guidelines.

You can call the above like this:

http://localhost:55223/addition?firstNumber=1&secondNumber=6

If you want to be able to call it like this:

http://localhost:55223/addition/9/6

Then you need to make some changes to the WebApiConfig class. Add this to code before the code for DefaultApi:

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

Above we are telling the routing engine: Hey routing engine, if the url contains the word api/addition followed by a variable and another variable, then use the Get method of the Addition controller*.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Hi, thank you so much for this answer. One of the best explanation :) – Susmitha Naidu Oct 30 '17 at 06:12
  • How do i call the java web service? – Susmitha Naidu Nov 01 '17 at 09:31
  • @susmithanaidu I thought that part was working already. Does this not work: `restfulClient.addition(firstNumber, secondNumber);`? – CodingYoshi Nov 01 '17 at 14:49
  • When i put that code into the AdditionController : ApiController, it does not work. It gives errors. When it is under the controller that i created previously (ApiController : Controller), it works. – Susmitha Naidu Nov 02 '17 at 00:38
  • When i use the codes in your answer, the parameters work fine. Only problem is that i get errors when i call the java web service. – Susmitha Naidu Nov 02 '17 at 00:45
  • Lets say i return the java web service using these codes: `var result = restfulClient.addition(firstNumber, secondNumber); return (result);` – Susmitha Naidu Nov 02 '17 at 03:37
  • I get error when i return the result. Error says `Cannot implicitly convert type 'System.Threading.Tasks.Task to 'System.Web.IHttpActionResult'.` – Susmitha Naidu Nov 02 '17 at 03:38
  • I have edited the answer. I thought you would be able to tweak the code to fit your needs and that is why I did not include the async part in my answer. – CodingYoshi Nov 02 '17 at 03:58