0

I have a MVC 5 application and I can register a user.

Now, I want to access a Web Api 2 with these credentials. I added Web api 2 just like in this thread

And this is my api

public class MyApiController : ApiController
{
    [Authorize]
    //[System.Web.Mvc.Authorize]
    public ResultContainer Get()
    {
        var result = new ResultContainer 
        {
            IsOk = true,
            DisplayMessage = false,
        };
        return result;
    }
}

Now, I want to access the api with a .net client (.net 4) with an account I registered from the website.

This is the code

var handler = new HttpClientHandler { Credentials = new NetworkCredential(Username, Password) };
            using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseUri) })
            {
                try
                {
                    var response = client.GetAsync("/api/MyApi").Result;  // Blocking call!
                    if (response.IsSuccessStatusCode)
                    {
                        var result = response.Content.ReadAsStringAsync().Result;
                    }
                 }
             }

The problem is that I always receive an html page with the form to login instead of the resource I wanted. I can access the api if I don't set the

Authorize

attribute. What am I missing?

Thanks

Community
  • 1
  • 1
Daniel
  • 9,312
  • 3
  • 48
  • 48

0 Answers0