locked
Redirect from one WebAPI to an another WebAPI and getting the response RRS feed

  • Question

  • User411771660 posted

    I want to create lets say a master/core api.Want to check for a certain parameter value and redirect to a an external api hosted in the same server.I have an api with uri http://hello.test.com/auth which takes two auth params Username and Password.Now i add a third parameter lets say Area.

    {
    "Username":"jason",
    "Password":"bourne",
    "Area":"mars"
    }

    Now coming to the master api, if with this uri for example http://master.test.com/v1/mster and i pass Username, Password and Area,and if the Area has value of lets say "mars" it should call the external mars api having uri http://mars.test.com/auth ,do the auth the process and return the response in the master api.is this possible?

    With my /auth api i have this controller returning the response :

     [HttpPost]
            [Route(ApiEndpoint.AUTH)]
            public HttpResponseMessage Auth(Login authBDTO)
            {
                if (!ModelState.IsValid)
                    return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
    
                using (AccountBusinessService accountService = new AccountBusinessService())
                {
                    var result = accountService.Auth(authBDTO);
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }
            }
    

    Sunday, July 21, 2019 12:31 PM

Answers

  • User283571144 posted

    Hi tarun02,

    According to your description, I suggest you could try to use Newtonsoft.Json package to covnert the model to json to make sure the json format is right.

    For example, you could refer to below codes:

    Create a userclass:

        public class Userclass
        {
            public string user { get; set; }
            public string password { get; set; }
           public string coop { get; set; }
    
           
        }

    Use below codes to convert the class to json.

                Userclass u1 = new Userclass() { user = auth.UserName,  password = auth.Password, coop= auth.Coop };
                string json = JsonConvert.SerializeObject(u1);

    Details codes:

            [HttpPost]
            [Route(ApiEndpoint.SAS)]
            public HttpResponseMessage esp(Login auth)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://sastest.test.com");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                var reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(auth, Formatting.Indented));
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                   Userclass u1 = new Userclass() { user = auth.UserName, password = auth.Password, coop= auth.Coop };
    string json = JsonConvert.SerializeObject(u1); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } return null; }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 23, 2019 6:30 AM

All replies

  • User1120430333 posted

    You can use HttpClient() normally using  it in connection of WebAPI client to a WebAPI service, The one WebAPI becomes a client to the other WebAPI. 

    https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#examples

    WebAPI client, which happens to be used in ASP.NET MVC project, is calling methods on an ASP.NET WebAPI service. The DTO is known between the WebAPI client and WebAPI service.

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Entities;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace ServiceLayer
    {
        public class ArticleSvc :IArticleSvc
        {
            public List<DtoArticle> GetAll()
            {
                var dtoarticles = new List<DtoArticle>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/article/GetAll");
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic articles = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in articles)
                    {
                        DtoArticle dto = obj.ToObject<DtoArticle>();
    
                        dtoarticles.Add(dto);
                    }
                }
    
                return dtoarticles;
            }
    
            public List<DtoArticle> GetArticlesByAuthorId(int id)
            {
                var dtoarticles = new List<DtoArticle>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/article/GetArticlesByAuthorId?id=" + id);
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic articles = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in articles)
                    {
                        DtoArticle dto = obj.ToObject<DtoArticle>();
    
                        dtoarticles.Add(dto);
                    }
                }
    
                return dtoarticles;
            }
            public DtoArticle Find(int id)
            {
                DtoArticle dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/article/Find?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic article = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = article.ToObject<DtoArticle>();
                }
    
                return dto;
            }
    
            public void Add(DtoArticle dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/article/Add", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Update(DtoArticle dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/article/Update", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Delete(DtoId dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/article/Delete", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
        }
    }
    

    Monday, July 22, 2019 1:15 AM
  • User283571144 posted

    Hi tarun02,

    Now coming to the master api, if with this uri for example http://master.test.com/v1/mster and i pass Username, Password and Area,and if the Area has value of lets say "mars" it should call the external mars api having uri http://mars.test.com/auth ,do the auth the process and return the response in the master api.is this possible?

    It possbile, you could send the http request in web api to another web api by using httpclient library. 

    You could write the codes inside the auth method to check the area , then you could use below codes to send the request to another web api. At last, you could generate the response according to another web api returned response.

    More details about how to send the request, you could refer to below codes:

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"user\":\"test\"," +
                      "\"password\":\"bla\"}";
    
        streamWriter.Write(json);
    }
    
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }

    Best Regards,

    Brando

    Monday, July 22, 2019 1:52 AM
  • User411771660 posted
    sir,there are multiple apis for different customers which is consumed by a mobile client.So instead of creating individual app for different customer,i want lets say a dropdown list in the said mobile app with username,password and AREA.area will define the said api in my server.so if the request comes with "mars" value for the area, i want to call the api from mars.test.com/auth and return the response.
    Monday, July 22, 2019 4:05 AM
  • User1120430333 posted

    sir,there are multiple apis for different customers which is consumed by a mobile client.So instead of creating individual app for different customer,i want lets say a dropdown list in the said mobile app with username,password and AREA.area will define the said api in my server.so if the request comes with "mars" value for the area, i want to call the api from mars.test.com/auth and return the response.

    It's called using routing in the WebAPI, like test.com/api/mars/auth.

    Here is a VB.NET example using WebAPI 2, but instead of using HttpClient() I am using WebClient(), along with using ActionName attribute. I think  you should be able to understand the concept, even if it's in VB.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

    Imports System.Net
    Imports Entities
    Imports Newtonsoft.Json
    
    Namespace WebApi
        Public Class WebApi
            Implements IWebApi
    
            #Region "Project"
            public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
           
            public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi
    
                dim dto as DtoProject
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                    dto = project
                End Using
               
                Return dto
    
            End Function
    
            public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    
            public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
            #End Region
    
            #Region "Task"
    
            public function GetTasksByProjIdApi(id as int32) as List(Of DtoTask) Implements IWebApi.GetTasksByProjIdApi
    
                Dim dtotasks = new List(Of DtoTask)
    
                dim url = "http://localhost/WebApiVB/api/task/GetTasksByProjectId?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim tasks = JsonConvert.DeserializeObject(of List(Of DtoTask))(json)
                    dtotasks = tasks
                End Using
    
                Return dtotasks
    
            End function
            
            public Function  GetTaskByIdApi(id As int32) As DtoTask Implements IWebApi.GetTaskByIdApi
    
                dim dto as DtoTask
    
                dim url = "http://localhost/WebApiVB/api/task/GetTaskById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim task = JsonConvert.DeserializeObject(of DtoTask)(json)
                    dto = task
                End Using
    
                return dto
    
            End Function
    
            public sub CreateTaskApi(dto As DtoTask) Implements IWebApi.CreateTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/CreateTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
              
            End sub
            
            public sub UpdateTaskApi(dto As DtoTask) Implements IWebApi.UpdateTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/UpdateTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub DeleteTaskApi(dto As DtoId) Implements IWebApi.DeleteTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/DeleteTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
            #End Region  
            
            #Region "Cache"
    
            public Function  GetCacheApi() As DtoCache Implements IWebApi.GetCacheApi
    
                dim dtocache = new DtoCache()
    
                dim url = "http://localhost/WebApiVB/api/cache/GetCache"
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim deserialized = JsonConvert.DeserializeObject(of DtoCacheRoot)(json)
    
                    dtocache.ProjectTypes = deserialized.DtoCache.ProjectTypes
                    dtocache.Durations = deserialized.DtoCache.Durations
                    dtocache.Statuses = deserialized.DtoCache.Statuses
                    dtocache.Resources = deserialized.DtoCache.Resources
    
                End Using
    
                return dtocache
    
            End Function
            #End Region
    
        End Class
    End Namespace
    
    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class ProjectController
            Inherits ApiController
    
            Private ReadOnly _daoproject As IDaoProject
    
            public sub New (daoproject As IDaoProject)
                _daoproject = daoproject
            End sub
    
            <HttpGet>
            <ActionName("GetProjectById")>
            public Function GetProjectById(ByVal id As Int32) As DtoProject
                return _daoproject.GetProjectById(id)
            End Function
    
    
            <HttpGet>
            <ActionName("GetProjectsByUserId")>
            public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
                return _daoproject.GetProjectsByUserId(userid)
            End Function
    
            <HttpPost>
            <ActionName("CreateProject")>
            public sub CreateProject(ByVal dto As DtoProject)
                Call _daoproject.CreateProject(dto)
            End sub
            
            <HttpPost>
            <ActionName("UpdateProject")>
            public sub UpdateProject(ByVal dto As DtoProject)
                Call _daoproject.UpdateProject(dto)
            End sub
    
            <HttpPost>
            <ActionName("DeleteProject")>
            public sub  DeleteProject(ByVal dto As DtoId)
                Call _daoproject.DeleteProject(dto.Id)
            End sub
            
        End Class
    End Namespace

    Monday, July 22, 2019 5:33 AM
  • User411771660 posted

    Hello sir,

    How do i pass parameter from the body in here

    string json = "{\"user\":\"test\"," +
                      "\"password\":\"bla\"}";

    My parameter comes from 

    public HttpResponseMessage esp(Login auth) //

    Monday, July 22, 2019 6:29 AM
  • User1120430333 posted

    Hello sir,

    How do i pass parameter from the body in here

    string json = "{\"user\":\"test\"," +
                      "\"password\":\"bla\"}";
    

    My parameter comes from 

    public HttpResponseMessage esp(Login auth) //

    Hello sir,

    How do i pass parameter from the body in here

    string json = "{\"user\":\"test\"," +
                      "\"password\":\"bla\"}";
    

    My parameter comes from 

    public HttpResponseMessage esp

    (Login auth) //

    So why can't you use a DTO known by the client and the service, Json serialize the DTO and send the DTO, which the code I have presented in C# and VB is Json serializing the DTO or deserializing a DTO sent by the service? You must know what a DTO is as your code seems to be using one. The DTO usage is a example of using Encapsulation.

     https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

    Monday, July 22, 2019 7:23 AM
  • User411771660 posted

    I tried this :

            [HttpPost]
            [Route(ApiEndpoint.SAS)]
            public HttpResponseMessage esp(Login auth)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://sastest.test.com");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                var reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(auth, Formatting.Indented));
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"user\":" + auth.UserName +
                                  "{\"password\":"+ auth.Password +
                                  "\"coop\":" + auth.Coop;
    
    
                    streamWriter.Write(json);
                }
    
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
                return null;
            }

    Monday, July 22, 2019 7:38 AM
  • User283571144 posted

    Hi tarun02,

    According to your description, I suggest you could try to use Newtonsoft.Json package to covnert the model to json to make sure the json format is right.

    For example, you could refer to below codes:

    Create a userclass:

        public class Userclass
        {
            public string user { get; set; }
            public string password { get; set; }
           public string coop { get; set; }
    
           
        }

    Use below codes to convert the class to json.

                Userclass u1 = new Userclass() { user = auth.UserName,  password = auth.Password, coop= auth.Coop };
                string json = JsonConvert.SerializeObject(u1);

    Details codes:

            [HttpPost]
            [Route(ApiEndpoint.SAS)]
            public HttpResponseMessage esp(Login auth)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://sastest.test.com");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                var reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(auth, Formatting.Indented));
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                   Userclass u1 = new Userclass() { user = auth.UserName, password = auth.Password, coop= auth.Coop };
    string json = JsonConvert.SerializeObject(u1); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } return null; }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 23, 2019 6:30 AM
  • User411771660 posted

    This worked :

    Route(ApiEndpoint.SAS)]
        public IHttpActionResult esp(Login auth)
        {
            if (auth.Coop == "PMC")
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60069/api/v1/auth");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new
                    {
                        Username = auth.UserName,
                        Password = auth.Password
                    });
    
                    streamWriter.Write(json);
                }
    
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
    
                    var result = streamReader.ReadToEnd();
                    dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(result);
                    obj.BaseUrl = "http://localhost:60069/api/v1";
    
                    return Ok(obj);
    
                }
    
            }

    Wednesday, July 24, 2019 6:10 AM