我正在使用已创建为ASP.Net Web应用程序的项目,其中启用了“Web API”模板和“个人用户帐户”作为身份验证选项。我有一个消耗web api的控制台应用程序。但是当我想获得令牌时,它会给我一个完整的html字符串,其中包含#34; 404未找到"而不是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);
}
答案 0 :(得分:0)
经过几天的思考和尝试。我找到了一个适合我的解决方案。在我之前的代码中,它仅适用于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();
}
}
}
我希望它可以帮助其他人解决同样的问题。