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.

2
  • 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. Commented Sep 21, 2015 at 16:26
  • Have you setup your project with WebAPI Controller classes? Commented Sep 21, 2015 at 16:37

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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
@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?
Is there anyway we can take this into chat? You might be able to clear up some of the questions I have.
|
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 }
);

6 Comments

This example is exactly what I need. Since I am not talking to the API through js.
I looked at the example you posted, and then additionally asp.net/web-api/overview/older-versions/… 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.
you can set a GET operation than returns the list of strings, blogs.msdn.com/b/martinkearn/archive/2015/01/05/… if you dont need a restful API (implementing verbs) , you can define custom methods too and call it directly but it isn't restful stackoverflow.com/questions/9569270/…
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.
Yes, in the first link you can see a function than return a string list (i.e.) public IEnumerable<string> 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)
|
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.