2

I have an asp.net webforms application as my UI layer. This application is responsible for sending an object list down to my DAL Class Library which will then send this object list to a WebAPI for processing.

The WebAPI needs to retrieve the object list, do the processing and send an OK status code back.

Is this possible? If is there any good documentation on how this is done?

Here is what I have in my webforms app:

public static async Task<bool> MyFunction(IList<string> Ids)
{
    using (var client = new HttpClient())
    {
        bool success = false;

        client.BaseAddress = new Uri("http://localhost:9000/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = await client.GetAsync("api/products/MyProcessFunctionName");
        if (response.IsSuccessStatusCode)
        {
            success = true;
        }

        return success;
    }
}

I need to figure out how to send the list of string Ids to the WebApi processing function as a parameter.

William Venice
  • 329
  • 2
  • 7
  • 16
  • Why wouldn't it be possible? If it's a .NET application just use `HttpClient` (or `HttpWebRequest` if it's your preference) to call the target web-service. – Dai Sep 21 '15 at 16:26
  • Have you setup your project with WebAPI Controller classes? – JGV Sep 21 '15 at 16:37

3 Answers3

2

I assume that you already know how to setup Web API controller in your project.

Here is a code sample for sending data from UI back to Web API controller method, which will then save that data in database,

Step 1:

In your front-end, I hope you will have a custom javascript file which handles any button click event. On that, try to send the data from UI to Web API using a POST method as shown below,

            var StaffSaveRequest = {};
            StaffSaveRequest.StaffDetails = {};
            StaffSaveRequest.StaffDetails.Name = "Test Name";

            $.ajax({
                url: 'api/Staff/SaveStaff', //this is the path to web api controller method
                type: 'POST',                   
                dataType: 'json',
                data: StaffSaveRequest,
                success: function (response, textStatus, xhr) {
                    //handle success 
                },
                error: function (xhr, textStatus, errorThrown) {                        
                    if (textStatus != 'abort') {
                      //handle error
                    }
                }
            });

Step 2:

Add a controller class as shown below and see the inline comments. This controller class will then interact with method in Data Access layer for saving any information.

    public class StaffController : ApiController //inherits ApiController 
    {
        [HttpPost] //add post attribute
        public HttpResponseMessage SaveStaff(StaffSaveRequest staffSaveRequest)
        {
            try
            {            
                var result = StaffManager.Save(staffSaveRequest);//save in database using a method in data access layer
                return Request.CreateResponse(HttpStatusCode.OK, result);//result the response back
            }
            catch (Exception ex)
            {
               //log error
            }
        }

I hope this will give you some idea on where and how to start. Reply back, if you still have issues/questions.

JGV
  • 5,037
  • 9
  • 50
  • 94
  • 1
    Thanks for the answer. In Step 1 in the code-behind of my page I want to send a list of selected Ids to the WebApi. I don't think I need JavaScript in this case do I? Step 2 is very easy to follow. – William Venice Sep 21 '15 at 17:26
  • I am pretty sure I have a good understanding of how to setup my Controller class. I think the confusion comes in when I would like to send a request to the WebAPI from a class file, not an html/aspx page. – William Venice Sep 21 '15 at 17:40
  • To be a bit more specific I am passing the WebApi something similar to a dictionary format. It is a list of string that will have multiple items in it that look like this: 123|113, 888|333, 212, etc. The WebApi will process each group of Ids – William Venice Sep 21 '15 at 17:46
  • @WilliamVenice, regarding your first comment, how are you calling the Web API method from your code behind? If you already have code, please share it. Also, I understand that you are trying to pass a dictionary to Web API method. But, how that dictionary is build? – JGV Sep 21 '15 at 17:53
  • Is there anyway we can take this into chat? You might be able to clear up some of the questions I have. – William Venice Sep 21 '15 at 18:08
  • I added an example to my post. – William Venice Sep 21 '15 at 18:30
1

You can use the Microsoft.AspNet.WebApi.Client to use your restful API. Here is an official example from the asp.net site:

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

If you need call your custom function MyProcessFunction first you need to define the function in the controller

 public IEnumerable<string> MyProcessFunctionName()
 {
 return new string[] { "value1", "value2" };
 }

after that, if you need to call it by name client.GetAsync("api/products/MyProcessFunctionName") you need to change the RouteConfig file to allow API calls by action name:

Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { action = "get", id = RouteParameter.Optional }
);
Community
  • 1
  • 1
kamus
  • 797
  • 1
  • 6
  • 15
  • This example is exactly what I need. Since I am not talking to the API through js. – William Venice Sep 21 '15 at 18:01
  • I looked at the example you posted, and then additionally http://www.asp.net/web-api/overview/older-versions/creating-a-web-api-that-supports-crud-operations which explains how to setup CRUD operations in an API controller. In my case I do not need CRUD operations, I still don't understand how in a GET request I pass a list of string to function in my Controller which is in the WebApi. – William Venice Sep 21 '15 at 18:49
  • you can set a GET operation than returns the list of strings, http://blogs.msdn.com/b/martinkearn/archive/2015/01/05/introduction-to-rest-and-net-web-api.aspx if you dont need a restful API (implementing verbs) , you can define custom methods too and call it directly but it isn't restful http://stackoverflow.com/questions/9569270/custom-method-names-in-asp-net-web-api – kamus Sep 21 '15 at 18:54
  • Thanks again for more useful resources, but is there anything that will show me how to send a List of string or Object List to a function in my controller. All of the examples I see either call a function by name or pass an Id. i.e. api/products/MyFunction or api/products/1, please see my updated code of what I have. – William Venice Sep 21 '15 at 19:01
  • Yes, in the first link you can see a function than return a string list (i.e.) public IEnumerable MyProcessFunctionName() { return new string[] { "value1", "value2" }; } and in the stackoverflow link you can see how to modify your route config to call the function by name (updated answer) – kamus Sep 21 '15 at 19:11
  • I think I found what I am trying to do in this post: http://www.codeproject.com/Tips/710116/Passing-Object-Collections-to-ASP-NET-Web-API Meaning I think a POST to my controller is what I am trying to do.Thank you very much for your help – William Venice Sep 21 '15 at 19:15
0

It's possible to call WebApi from your webforms project. Here is a sample using WPF to call WebApi, but call should be same for webforms: http://www.codeproject.com/Articles/611176/Calling-ASP-Net-WebAPI-using-HttpClient

Paritosh
  • 4,243
  • 7
  • 47
  • 80