mardi 27 août 2019

How to write .net web api controller to consume and expose another web api

I need to wrap an api call with my own api to avoid CORS and so I can avoid exposing credentials to the client. Can anyone help me to figure out what I'm doing wrong?

This works in a webform but I don't know how to put its an api controller class. When I try to return the objects with the code below it throws an error

Controller
public class sampleController : ApiController
{
    public IEnumerable<sample> GetSample() 
    {

        string url = String.Format("sampleurl.json");
        WebRequest requestObj = WebRequest.Create(url);
        requestObj.Credentials = new NetworkCredentials("USER", "PW");
        requestObj.Method = "GET";
        HttpWebResponse responseObj = null;
        responseObj = (HttpWebResponse)requestObj.GetResponse();
        string str = null;
        using (Stream stream = responseObj.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            str = sr.ReadToEnd();
            sr.Close();
        }

        var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        sample sampleList = (sample).ser.Deserializer(str, typeof(sample));

        return sampleList.Root_Object;

    }    

}


Model
public class sample
{
    public List<Root_Object> Root_Object {get; set;}
}

public class Root_Object
{
    public string listItemOne { get; set; }
    public string listItemTwo { get; set; }
}

I expected to be able to return all objects from Root_Object. The return statement gives me an error of "Cannot implicitly convert type 'System.Collections.Generic.IList' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists(are you missing a cast?)"




Aucun commentaire:

Enregistrer un commentaire