简体   繁体   中英

Creating input parameters and using java web service function in ASP.NET Web API

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.

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*.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM