locked
Web Api trouble RRS feed

  • Question

  • User109965461 posted

    Hello Everyone,

    For my assignment I need to allow a browser help object access my web api that I've created. I've tried every way imaginable. One a website that I have to access, my www.myuhc.com    my computer should get that information from my web api and send to the website to login. This is my way of calling the request through the BHO. It just sits on the website and doesn't seem to do anything. I have more code if you need some.     

    I was using Httpwebrequest to call my web api and it still won't call it. I've put code to autofill the box and it won't even fill, when it's after the request, but when I remove the request the code will fill it. So it's getting stuck on the web request and I can't seem to understand why it's not getting my data from my web api. I'm fairly new to Web Api. Do I need something certain when sending web api across a website link. Anything can help.

    Thanks

    Wednesday, August 23, 2017 7:07 PM

All replies

  • User-271186128 posted

    Hi Bennyyboyy,

    Bennyyboyy

    I was using Httpwebrequest to call my web api and it still won't call it. I've put code to autofill the box and it won't even fill, when it's after the request, but when I remove the request the code will fill it. So it's getting stuck on the web request and I can't seem to understand why it's not getting my data from my web api. I'm fairly new to Web Api. Do I need something certain when sending web api across a website link. Anything can help.

    From your description, it seems that the issue is that you want to know how to call the web API and get the value. If that is the case, I suggest you could refer to the following methods:

    1. Using JQuery Ajax:

    Code in Web API controller:

    public class TestController : ApiController
    {
            [HttpGet]
            public List<string> Get()
            {
               string userName = "Peter";
               string  password = "123";
                List<string> list = new List<string>();
                list.Add(userName);
                list.Add(password);
                return list;
            }
       }
    

    Code in View:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script>
            function GetLogin() {  
                $.ajax({
                    type: "Get",
                    url: 'http://localhost:64186/api/Test',//change to your url
                    contentType: 'application/json',
                    success: function (data) {
                        alert(JSON.stringify(data));
                        for (var i = 0; i < data.length; i++) {
                            var userName = data[0];
                            var password = data[1];
                        }
                        document.getElementById("userName").value = userName;
                        document.getElementById("password").value = password;
                    }
                });
            }
    
        </script>
    </head>
    <body>
        <input type="button" value="GetLogin" onclick="GetLogin()" /><br />
        <input type="text" id="userName"/><br />
        <input type="password" id="password"/><br />
        <input type="button" value="Login"/>
    </body>
    </html>
    

    You could see the result like this:

    Besides, you could also try to use HttpClient.

    Code in Web API controller:

            Item[] items = new Item[]
            {
    
                new Item{Id = 1,name="Apple", Type="Fruit",cost=100},
    
                new Item{Id = 2,name="Tomato",Type="vasitable",cost=50},
    
            new Item {Id = 3,name="T-Shirt",Type="cloths",cost=500}
    
            };
            List<Item> itemlist = new List<Item>()
            {
                 new Item{Id = 1,name="Apple", Type="Fruit",cost=100},
    
                new Item{Id = 2,name="Tomato",Type="vasitable",cost=50},
    
            new Item {Id = 3,name="T-Shirt",Type="cloths",cost=500}
            };
            [AllowAnonymous]
            public IEnumerable<Item> GetAllItems()
            {
                return itemlist;
            }

    C# code:

                HttpClient client;
                string url = "http://localhost:53122";
                client = new HttpClient();
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync(string.Format("/api/items/")).Result;
                if (response.IsSuccessStatusCode)
                {
                    // Modify as per your requirement    
                    List<Item> emp = new List<Item>();
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    emp = JsonConvert.DeserializeObject<List<Item>>(responseString);
                    // Your code goes here      
                }

    More details, you could refer to the following articles:

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

    http://www.c-sharpcorner.com/article/calling-web-api-using-httpclient/ 

    Edit:

    For my assignment I need to allow a browser help object access my web api that I've created. I've tried every way imaginable. One a website that I have to access, my www.myuhc.com    my computer should get that information from my web api and send to the website to login.

    From your description, because the two applications are hosted at different domains, an AJAX request from WebClient to WebService is a cross-origin request.

    More details, see: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    Best regards,
    Dillion

    Thursday, August 24, 2017 8:49 AM
  • User109965461 posted

    I kind of figured out most of the code to do it I'm just trying to figure out the best route for sending web api to that content. I could inject code into it through the browser helper object so i'm wondering it I would be able to inject the ajax call into the websites code and call me web api or do something like httpclient to access my web api. is CORS more for ajax? I'm trying to do something as simple as an alert to check for the success that I've accessed the web api. Here's what my ajax looks like:

    @"$.ajax({
                    type: ""GET"",
                    url: 'http://localhost:64186/api/Tables1/1',
                    contentType: 'application/json',
                    success: function(data) {
                            alert('success!');
                });";

    Here's my HttpGet:

    [HttpGet]
            [ResponseType(typeof(Table))]
            public IHttpActionResult GetTable(int id)
            {
                Table table = db.Tables.Find(id);
                if (table == null)
                {
                    return NotFound();
                }

                return Ok(table);
            }

    Thursday, August 24, 2017 2:52 PM
  • User-271186128 posted

    Hi Bennyyboyy,

    I could inject code into it through the browser helper object so i'm wondering it I would be able to inject the ajax call into the websites code and call me web api or do something like httpclient to access my web api.

    Does the websites is created by yourself? How do you inject the Ajax call into the websites?

    If the website is created by you. Could you provide code about your website?

    is CORS more for ajax?

    If your website and web api are different projects, I think yes. It’s CORS.

    I'm trying to do something as simple as an alert to check for the success that I've accessed the web api. Here's what my ajax looks like:

    I’m not sure how do you inject the ajax code? If it is a simple ajax, you could refer to the following code:

    Code in Model:

    public class DiscountList
        {
            [Key]
            public int ID { get; set; }
            public string Name { get; set; }
        }
    

    Code in api Controller:

            [HttpGet]
            [ResponseType(typeof(DiscountList))]
            public IHttpActionResult GetTable(int id)
            {
                connStr db = new connStr();
                DiscountList dis = db.Discounts.Find(id);
                if (dis == null)
                {
                    return NotFound();
                }
    
                return Ok(dis);
            }
    

    Code in View:

    function GetLogin() {  
    $.ajax({
                    type: "GET",
                    url: 'http://localhost:64186/api/Test/1',
                    contentType: 'application/json',
                    success: function (data) {
                        //alert('success!');
                        alert(JSON.stringify(data));// get data from webapi:db.Discounts.Find(id);
                    }
                }); 
            }
    

    You could see the result like this:

    Best regards,
    Dillion

    Friday, August 25, 2017 7:59 AM
  • User109965461 posted

    No the website isn't created by me. It's someone else's www.myuhc.com. I'm supposed to access it via an internet explorer browser plug-in. and send the web api data to the browser plugin class and it plugs it in.  

    Friday, August 25, 2017 4:05 PM
  • User475983607 posted

    No the website isn't created by me. It's someone else's www.myuhc.com. I'm supposed to access it via an internet explorer browser plug-in. and send the web api data to the browser plugin class and it plugs it in.  

    What you are requesting seems illegal.

    You really should contact myuhc.com and make sure you are not breaking HIPPA rules.  

    Hopefully browsers have security mechanisms to detect plugins that try to send information to a different domain and stop the request.

    Monday, August 28, 2017 1:27 PM