我一直在學習如何授權在ASP.Net WebApi中工作,我遇到了另一篇文章(ASP.NET Web API Authentication)中Darin Dimitrov的回答,我需要一些幫助來理解爲什麼我得到一個401ASP.NET WebApi FormsAuthentication 401(未授權)問題
繼Darin的代碼,我創建了一個項目的WebAPI並添加以下控制器和型號:
AccountController.cs
using System.Web.Http;
using System.Web.Security;
using AuthTest.Models;
namespace AuthTest.Controllers
{
public class AccountController : ApiController
{
public bool Post(LogOnModel model)
{
if (model.Username == "john" && model.Password == "secret")
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return true;
}
return false;
}
}
}
UsersController.cs
個using System.Web.Http;
namespace AuthTest.Controllers
{
[Authorize]
public class UsersController : ApiController
{
public string Get()
{
return "This is top secret material that only authorized users can see";
}
}
}
LogOnModel.cs
namespace AuthTest.Models
{
public class LogOnModel
{
public string Username { get; set; }
public string Password { get; set; }
}
}
我已經創建了兩個按鈕,一個Web窗體應用程序,用於測試目的的標籤。
Default.aspx.cs
using System;
using System.Net.Http;
using System.Threading;
namespace AuthTestWebForms
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonAuthorizeClick(object sender, EventArgs e)
{
using (var httpClient = new HttpClient())
{
var response = httpClient.PostAsJsonAsync(
"http://localhost/authtest/api/account",
new { username = "john", password = "secret" },
CancellationToken.None
).Result;
response.EnsureSuccessStatusCode();
bool success = response.Content.ReadAsAsync<bool>().Result;
if (success)
{
//LabelResponse.Text = @"Credentials provided";
var secret = httpClient.GetStringAsync("http://localhost/authtest/api/users");
LabelResponse.Text = secret.Result;
}
else
{
LabelResponse.Text = @"Sorry, you provided the wrong credentials";
}
}
}
protected void ButtonTestAuthClick(object sender, EventArgs e)
{
using (var httpClient = new HttpClient())
{
var secret = httpClient.GetStringAsync("http://localhost/authtest/api/users");
LabelResponse.Text = secret.Result;
}
}
}
}
當我點擊按鈕,並運行ButtonAuthorizeClick()它觸發的賬戶控制器,然後觸發對用戶的控制,一切都很好。
如果我然後單擊ButtonTestAuthClick(),我得到一個401(未授權)錯誤。
當我在Chrome或FireFox中尋找ASPXAUTH cookie時,我沒有看到一個,所以我不能100%確定爲什麼ButtonAuthorizeClick()能夠工作,而我需要做什麼才能使ButtonTestAuthClick()工作。
感謝任何人的幫助可以拋開我的路。
Dang ...我的測試應用程序和api都有「Forms」設置,我仍然得到相同的響應。不過謝謝你的回答。 –
解決了我的問題,謝謝 – JGilmartin