2

Visual Studio 2015 を使用して Asp.net Core 1.0 (WebApi) プロジェクトを作成しています。テンプレートは ASP.NET Core Web アプリケーション (.NET Core)\WebApi (認証が選択されていません) です。

ここに画像の説明を入力

ValuesController で、そのメソッドを呼び出しているクライアントから Windows ID を取得したいと思います。

using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
...
[Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpGet]
        [Route("GetIdentity")]
        public string GetIdentity()
        {
            //method1
            var userId = User.GetUserId();
            //method2
            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            return userId;
        }
    }

method1現在、およびで期待どおりの結果が返されませんmethod2。何か考えがありますか?

4

1 に答える 1

3

認証がなければ、Web フレームワークはユーザーの身元を特定できません。

プロジェクト テンプレート"ASP.NET Core Application (.NET Core)\WebApi" を選択し、認証を " No Authentication" から任意の適切な認証(" " など) に変更しますWindows Authentication

次に、属性Userで注釈が付けられている場合、コントローラーのメンバーにアクセスできます。[Authorize]

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{        
    [HttpGet]
    public string Get()
    {
        return User.Identity.Name;
    }
}

個々のユーザー アカウントが必要な場合は、(WebAPI ではなく) MVC テンプレートを選択します。次に、個々のアカウントを登録し、それらの資格情報を認証に使用できます。

認証なしでテンプレートから開始した場合はlaunchSettings.jsonPropertiesフォルダー内の Windows 認証を有効にすることができます。

{
   "iisSettings": {
      "windowsAuthentication": true,
      "anonymousAuthentication": false,
      ...
    },
    ...
 }
于 2016-08-28T09:04:13.413 に答える