簡體   English   中英

檢索令牌ASP.NET Web API模板IIS 7.5 404時出錯

[英]Error retrieving token ASP.NET Web API template iis 7.5 404 not found

我正在使用一個已創建為ASP.Net Web應用程序的項目,其中已啟用“ Web API”模板和“個人用戶帳戶”作為身份驗證選項。 我有一個使用Web API的控制台應用程序。 但是,當我想獲取令牌時,它將為我提供一個完整的html字符串,其中包含“ 404 not found”,而不是json數組。 我究竟做錯了什么?

這是mij控制台應用程序代碼:

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;
            }
        }
    }
}

這是我的Startup.Auth:

 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {   
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

    }

經過幾天的思考和嘗試。 我找到了對我有用的解決方案。 在我以前的代碼中,它僅在iisexpress中有效(我不知道為什么,如果有人知道,請分享!)。 但是在我的新代碼中,它同時適用於iisexpress和iis 7.5。

using ConsoleApplication1.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
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";

    private static async void GetAPIToken()
    {
       string responseJson =  await ResponseAsStringAsync(string.Format("{0}/token", apiBaseUri),
            new[]
            {
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("grant_type", "password"),
            });

        var jObject = JObject.Parse(responseJson);
        string token = jObject.GetValue("access_token").ToString();            
    }

    public static async Task<string> ResponseAsStringAsync(string url, IEnumerable<KeyValuePair<string, string>> postData)
    {
        string responseString = string.Empty;

        var uri = new Uri(url);

        using (var client = new HttpClient())
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await client.PostAsync(uri, content);

            responseString = await response.Content.ReadAsStringAsync();
        }

        return responseString;
    }

    static void Main(string[] args)
    {
        GetAPIToken();           
        Console.ReadKey();
    }



}


}

我希望它可以幫助遇到相同問題的其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM