How to configure rest api’s in WCF project , making it hybrid solution

46 views Asked by At

I want to work on making a hybrid solution of an existing wcf project. How to figure it out any resources? How will i configure an existing contrat/service to use rest and comicate with another api to the frontend.

I have made a controller in the wcf solution and a webapiconfig file, globalasax file. What else do i need to do

1

There are 1 answers

1
QI You On

Here are my steps you can refer to:

1.Install the relevant packages on Nuget

enter image description here

2.Add two classes

 public class RouteConfig
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapRoute(
             name: "Default",
         url: "{controller}/{action}/{id}",
             defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
         );
     }
 }



public static class WebApiConfig
 {
     public static void Register(HttpConfiguration config)
     {
         // Web API configuration and services

         // Web API routes
         config.MapHttpAttributeRoutes();

         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional }
         );
     }
 }

3.Add a Global.asax

protected void Application_Start(object sender, EventArgs e)
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof("yourservicename")));
}

4.Add API Controller

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "WCFTest";
    }

    // POST api/values
    public void Post([FromBody] string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

5.Output: enter image description here enter image description here