检索到令牌ASP.NET Web API模板iis 7.5 404时找不到错误(Error retrieving token ASP.NET Web API template iis 7.5 404

编程入门 行业动态 更新时间:2024-10-26 03:31:09
检索到令牌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); }

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

This is my 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(); } } }

我希望它可以帮助其他人解决同样的问题。

After a couple of days thinking and trying. I found a solution that worked for me. In my previous code it worked only in iisexpress (I don't know why so if someone knows please share!). But in my new code it worked for both iisexpress and 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(); } } }

I hope it helps someone else with the same problem.

更多推荐

本文发布于:2023-07-31 02:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:找不到   令牌   模板   错误   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!