アップデート:
コードを に変更しましたFormsAuthentication.SetAuthCookie(_model.UserName, true);
。1 つは MVC 用、もう 1 つは WebAPI 用です。MVC 構成で、私は定義します
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
両方のアプリケーションが同じドメインにあります。
更新: WebAPI で Cookie を使用する必要がありますか?
現在、フォーム認証と WebAPI プロジェクトを使用する MVC プロジェクトがあります。問題は、WebAPI プロジェクトで要求に関連付けられたユーザーを取得できないことです。これは可能だと思いましたか、それとも実装が間違っているのでしょうか?
注: テストとして WebAPI コントローラー メソッドに Cookie コードを入れましたが、本来あるべき場所ではありません。
MVC - ログイン要求を処理し、認証チケットを作成します。
// POST: /Account/Login
[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel _model, string _returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(_model.UserName, _model.Password))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(_model.UserName, true, 15);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
// set redirect
}
}
// If we got this far, something failed, redisplay form
return View(_model);
}
WebAPI - 更新リクエストを処理します
[AcceptVerbs("PUT")]
public HttpResponseMessage UpdateInfo(int _id, ExampleModel _model)
{
try
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
// decrypt the ticket if possible.
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket);
var userData = ticket.UserData;
}
}
// do update
return Request.CreateResponse(HttpStatusCode.OK, data, GlobalConfiguration.Configuration);
}
catch (Exception err)
{
m_logger.Error(err);
throw;
}
}