Search code examples
c#asp.net-web-apiasp.net-web-api-routing

How to Add API controller (Web API 2) in Asp.Net (aspx) application C#


I have a asp.net (aspx) c# web application on .net framework 4.5, I have to create a web api in this application that will consume in third party CMS(Infusionsoft) Http POST campaign.


Solution

  • To add webapi controller in asp.net C# application

    Step 1: Add new webapi controller using Add New Item process enter image description here

    Step 2: Added PaymentController

     public class PaymentController : ApiController
        {
            // GET api/<controller>
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/<controller>/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/<controller>
            public void Post([FromBody]string value)
            {
            }
    
            // PUT api/<controller>/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE api/<controller>/5
            public void Delete(int id)
            {
            }
        }
    

    Step 3: Add Routing information in Application_stat methd inside Global.asax.cs file

    Add Using namespaces:

    using System.Web.Http;
    using System.Web.Routing;
    
    
    
     protected void Application_Start(Object sender, EventArgs e)
            {
                RouteTable.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = System.Web.Http.RouteParameter.Optional }
                    );
            }
    

    Step 4: Run application and it will raise below exception:

    Attempt by security transparent method 'DebtFREE.Global.Application_Start(System.Object, System.EventArgs)' to access security critical field 'System.Web.Http.RouteParameter.Optional' failed. Assembly 'DebtFREE, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

    enter image description here

    Step 5: Go to AssemblyInfo.cs (Bin/Properties/AssemblyInfo.cs) and comment below line. enter image description here [assembly: AllowPartiallyTrustedCallers]

    Step 6: Cheers, run application and browse url: http://localhost:2071/api/payment API is wokring togather aspx (asp.net) application.

    enter image description here