locked
Error retrieving token ASP.NET Web API template (iis 7.5 error 404 not found) RRS feed

  • Question

  • User-844201490 posted

    I’m working with a project that has been created as a ASP.Net Web Application with the ‘Web API’ template and ‘Individual User Accounts’ enabled as the authentication option. I have a console application that consumes the web api. But When I want to get the token it gives me an html string with 404 not found in stead of a json array. What am I doing wrong?

    This is mij console app code:

    using ConsoleApplication1.Helpers;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
    {
        const string userName = "user@user.com";
        const string password = "Password01!";
        const string apiBaseUri = "http://localhost/WebAPITest";
        const string apiGetPeoplePath = "/api/people";
    
        static void Main(string[] args)
        {
            //Get the token
            var token = GetAPIToken(userName, password, apiBaseUri).Result;
            Console.WriteLine("Token: {0}", token);
    
            //Make the call
            var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result;
            Console.WriteLine("response: {0}", response);
    
            //wait for key press to exit
            Console.ReadKey();
        }
    
        private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
        {
            using (var client = new HttpClient())
            {
                //setup client
                client.BaseAddress = new Uri(apiBaseUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                //setup login data
                var formContent = new FormUrlEncodedContent(new[]
                {
     new KeyValuePair<string, string>("grant_type", "password"),
     new KeyValuePair<string, string>("username", userName),
     new KeyValuePair<string, string>("password", password),
     });
    
                //send request
                HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);
    
                //get access token from response body
                var responseJson = await responseMessage.Content.ReadAsStringAsync();
                var jObject = JObject.Parse(responseJson);
                return jObject.GetValue("access_token").ToString();
            }
        }
    
        static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
        {
            using (var client = new HttpClient())
            {
                //setup client
                client.BaseAddress = new Uri(apiBaseUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
    
                //make request
                HttpResponseMessage response = await client.GetAsync(requestPath);
                var responseString = await response.Content.ReadAsStringAsync();
                return responseString;
            }
        }
    }
    
    }



    Am I missing something? 

    Sunday, September 11, 2016 1:15 AM

Answers

All replies

  • User36583972 posted

    Hi youssef.azarouali,

    But When I want to get the token it gives me an html string with 404 not found in stead of a json array. What am I doing wrong?

    As far as I know, We usually through the following steps to get the Token in Account Controller.

    1.Register users (use Register method available in AccountController)

    2.Login, you need to post data in following format to http://example.com/token (Which can be configured in StartUp.Auth.cs)

    grant_type=password&username=Alice&password=password123

    You can also try to use query string:

    var response = client.PostAsync("Token", new StringContent("grant_type=password&username=xxx&password=xxx1234", Encoding.UTF8)).Result;
    

    3.After login, you can recieve an bearer token, which you need to send with authorization header with every request to access protected resource.

    From your error message, API methods you visit not found, Please check your application correctly (url or route). The following tutorials for your reference.

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2:

    http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    Using Web API 2 (Individual User Account + CORS Enabled) from AngularJS Client:

    http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En

    Best Regards,

    Yohann Lu

    Monday, September 12, 2016 6:14 AM
  • User-844201490 posted

    Hi Yohan, thanks for your answer. I have figured it out that the code wasn't the problem. The web api works fine in development with iisexpress. But when I deploy it to IIS, it doesn't work anymore. It gives me 404 not found. I have tried to set this in my config:

     <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>

    But this didn't work. I'm lost right now. Do you have any idea where to look for?

    Friday, September 16, 2016 12:23 PM
  • User36583972 posted

    Hi youssef.azarouali,

    But when I deploy it to IIS, it doesn't work anymore. It gives me 404 not found

    Firstly, you should check your request url is correctly.

    Then, the following links for your reference.

    HTTP 404 Page Not Found in Web Api hosted in IIS 7.5:

    http://stackoverflow.com/questions/9703090/http-404-page-not-found-in-web-api-hosted-in-iis-7-5

    HTTP Error 404.0 - Not Found (MapRequestHandler / StaticFile) when deploying WCF Web API on IIS 7.x:

    https://alexanderzeitler.com/articles/HTTP-Error-4040---Not-Found-(MapRequestHandler--StaticFile)-when-deploying-WCF-Web-API-on-IIS-7x/

    Best Regards,

    Yohann Lu

    Monday, September 19, 2016 9:03 AM
  • User-844201490 posted

    Hi Yohann,

    Thanks for your answer but I have tried those already and still no success. Is it an iis setting that I'm missing? On the IIS asp.net is installed.

    Monday, September 19, 2016 9:30 AM
  • User-844201490 posted

    I finally have found a solution.  See the solution here:

    http://stackoverflow.com/questions/39396123/error-retrieving-token-asp-net-web-api-template-iis-7-5-404-not-found

    I hope this helps someone with the same problem.

    Gr. Youssef

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 21, 2016 11:24 AM