APIを使用してユーザーとしてログインし、特定のメソッドにアクセスする方法を理解するのに問題があります。
public class UsersController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(LoginModel model)
{
HttpResponseMessage Response = new HttpResponseMessage();
// check if all required fields are set
if (ModelState.IsValid)
{
// authenticate user
var success = Membership.ValidateUser(model.UserName, model.Password);
if (success)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
model.UserName,
DateTime.UtcNow,
DateTime.UtcNow.AddDays(1),
true,
"Api ticket",
FormsAuthentication.FormsCookiePath);
//Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
//Create the cookie.
CookieHeaderValue mycookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, encTicket);
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent)
mycookie.Expires = ticket.Expiration;
Response.Headers.AddCookies(new CookieHeaderValue[] { mycookie });
return Response;
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
//return View(model);
return Response;
}
[Authorize]
[HttpGet]
public string Get()
{
return User.Identity.Name;
}
}
私はFiddlerを使用しており、ユーザー名とパスワードを含むjsonオブジェクトを使用してこのメソッドに投稿します。デバッグすると、すべてが正常に実行され、次の応答が返されます。
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
Set-Cookie: .ASPXAUTH=4FDA2F2D23381CD0C9AD901BB8A9FE808254502F3BB9442CF80B67F318E7000A1C8B395A97616DBE893317072957F7E1790D81F8648C8472EA80AE2A5E60BE81F08F8C0BF07F2F1EB8E1C661EE56FB61FEA7FCD4D7AABF2718B58690D4D82B049B16126D44368429331D8E3138D533D4; expires=Wed, 27 Feb 2013 21:45:48 GMT
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcRGVjaXNpb25NYWtlclxEZWNpc2lvbk1ha2VyXGFwaVx1c2Vyc1w=?=
X-Powered-By: ASP.NET
Date: Tue, 26 Feb 2013 21:45:48 GMT
Content-Length: 0
Get()
ここから、401 Unauthorizedエラーを返さずにメソッドにアクセスするにはどうすればよいですか?GETに次のヘッダーを追加してください。
Cookie: .ASPXAUTH=4FDA2F2D23381CD0C9AD901BB8A9FE808254502F3BB9442CF80B67F318E7000A1C8B395A97616DBE893317072957F7E1790D81F8648C8472EA80AE2A5E60BE81F08F8C0BF07F2F1EB8E1C661EE56FB61FEA7FCD4D7AABF2718B58690D4D82B049B16126D44368429331D8E3138D533D4