0

I have a web api with a method to return string value. I am having this web api controller inside a web application. I am trying to call the method in the api using the following code:

        Stream data = client.OpenRead(new Uri("http://localhost:40786/api/Getvalues/getstring"));
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
        data.Close();
        reader.Close();

I am calling this method on click event of a web-page say Default.aspx. The code runs fine however instead of calling web-api and returning it's value, it is returning HTML mark-up of the page on which i have the button. No idea what is happening. Can anyone suggest what I am missing here ?

4
  • What string value localhost:40786/api/Getvalues/getstring supposed to return? Commented Aug 8, 2015 at 14:01
  • @Tech-jay you're trying to read the stream, so, you're getting what you're trying. If you need result and store/show at another place. Just tries its working for me: client.DownloadString("http://localhost:40786/api.Getvalues.getstring"); Commented Aug 9, 2015 at 7:21
  • Hello all, thnx for reply.I analysed the issue and let me add some more to it. I am trying to implement forms authentication in web-api. So I have login form with username/pwd option. User signs in and clicks the button to call web-api. The user is authenticated but still the string that is returned is html mark-up of the login page.On the other hand, when i call the web-api by setting url directly in browser, it allows the call, as the user has become authenticated. When signout, browser does not allows call. So browser based call is working but not sure how can implement this actually. Commented Aug 9, 2015 at 13:10
  • @TechJay - in that scenario try to use Tokenize authentication with webapi. Use JSON Web API Token to authenticate your incoming webapi calls. Try this google.co.in/?q=asp.net+web+api+json+web+token Commented Aug 9, 2015 at 13:41

1 Answer 1

1

Try this code:

WebClient client = new WebClient();
string resultStr = client.DownloadString(http://localhost:40786/api/Getvalues/getstring");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.