Ehsan Ghanbari

Experience, DotNet, Solutions

Call Asp.net Web API from C#

If you search in the web for calling web API from C# Code, not from URL, you will find lots of sample on getting and hard enough on the POST! I don't know why but I want to share with you a simple example. As a usual open visual studio and create a web API project from the MVC project template.

Suppose these two simple post and get API actions:     

   [HttpPost]

        [Route("api/Test/PostValue")]

        public IHttpActionResult PostValue([FromBody]string value)

        {

            //Persis in data base or what you want

            return Ok();

        }



        [HttpGet]

        [Route("api/Test/GetValue")]

        public IHttpActionResult GetValue()

        {

            //Fetch from data base

            return Ok();

        }

Now We want to post a data to the PostValue and get a data from GetValue considering the parameters of the Post is FromBody which means that you should send the target value from the body of your request not in Url in the case of calling by Postman or other tools. To call the above action methods from c#, simply create an instance of HttpClient and call the appropriate methods:

  public ActionResult Post()

        {

            var client = new HttpClient();

            var response = client.PostAsJsonAsync("http://localhost:52863/" + "/Api/Test/PostValue", "a value for api").Result;

            return View();

        }





        public ActionResult Get()

        {

            var client = new HttpClient();

            var response = client.GetAsync("http://localhost:52863/" + "/Api/Test/GetValue");

            return View();

        }

 or simply call them in a console application to see the result.



IP filtering attribute for web API

Recently I came up with a solution for filtering the API requests by filtering the server IP. This is used when you want to make the received requests private and secure. It's a simple helper and I hope it could be useful for you as well.

public class AuthorizeApiIPAddressAttribute : ActionFilterAttribute

    {

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

        {

            //Get users IP Address

            string ipAddress = HttpContext.Current.Request.UserHostAddress;



            if (!IsIpAddressValid(ipAddress.Trim()))

            {

                actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Unauthorized);

            }



            base.OnActionExecuted(actionExecutedContext);

        }



        /// <summary>

        /// Compares an IP address to list of valid IP addresses attempting to

        /// find a match

        /// </summary>

        /// <param name="ipAddress">String representation of a valid IP Address</param>

        /// <returns></returns>

        public static bool IsIpAddressValid(string ipAddress)

        {

            //Split the users IP address into it's 4 octets (Assumes IPv4)

            string[] incomingOctets = ipAddress.Trim().Split(new char[] { '.' });



            //Get the valid IP addresses from the web.config

            string addresses = Convert.ToString(AppSettingHelper.GetSetting("AuthorizedIPAddresses"));



            //Store each valid IP address in a string array

            string[] validIpAddresses = addresses.Trim().Split(new char[] { ',' });



            //Iterate through each valid IP address

            foreach (var validIpAddress in validIpAddresses)

            {

                //Return true if valid IP address matches the users

                if (validIpAddress.Trim() == ipAddress)

                {

                    return true;

                }



                //Split the valid IP address into it's 4 octets

                string[] validOctets = validIpAddress.Trim().Split(new char[] { '.' });



                bool matches = true;



                //Iterate through each octet

                for (int index = 0; index < validOctets.Length; index++)

                {

                    //Skip if octet is an asterisk indicating an entire

                    //subnet range is valid

                    if (validOctets[index] != "*")

                    {

                        if (validOctets[index] != incomingOctets[index])

                        {

                            matches = false;

                            break; //Break out of loop

                        }

                    }

                }



                if (matches)

                {

                    return true;

                }

            }



            //Found no matches

            return false;

        }

As you saw, it's an attribute that you can use it in web API.



Routing in asp.net Web API

If you have worked with asp.net MVC routing, you will find out that there are lots of similarities with asp.net web API and actually Web API uses the MVC standards on routing. There is only one difference and that's about using HTTP method in web API instead of URL path in MVC. In other word, Web API does not specify an action route parameter, bur it by default maps incoming requests to the appropriate action based upon the HTTP verb of the request.

Take a look at the following sample: 

[HttpPut]

public HttpResponseMessage Order(int Id, OrderDate date)

{

   // Not implement

}

In Order to define a route to this, you would act like this:

config.Routes.MapHttpRoute(

            name: "OrderRoute",

            routeTemplate: "Orders/{Id}/date"

            defaults: new { controller = "Orders", action = "Order" }

        );

The only difference you can find in comparison to MVC, is the using MapHttpRoute() instead of MapRoute(), right? Rather than that Attribute In WebApi2 is like in MVC. if you have visual studio 2013, you can create your Web API2 project template and get started working with attribute routing, otherwise, you can get the attribute routing via NuGet package manager by executing the below command:

PM> Install-Package AttributeRouting.WebApi

For example, you can define attribute routing for the above sample simply:

[Route("Order/{Id}/date")]

[HttpPut]

public HttpResponseMessage Order(int id, OrderDate)

{

}

Although URL routing in asp.net is something extensible, the routing rules are just what you see in the above. If you are using WebApi2 I advise you to use Attribute routing cause it has lots of advantages and solves lots of troubles of regular routing such as conflicting, readabilities,…. 

For complete information, you can refer to this article.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC