httpContext.User.Identity.Name Coming back as " "

本文关键字:quot as back Coming User Identity Name httpContext | 更新日期: 2023-09-27 18:25:19

我正试图从经过windows验证的MVC 5应用程序中获取用户名,但字符串一直返回为"或空。我可以在我的控制器中获得用户名,但当使用这个新类时,我无法检索它。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeMaster.CustomAttribute;

namespace EmployeeMaster.CustomAttribute
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var username = httpContext.User.Identity.Name.Substring(httpContext.User.Identity.Name.IndexOf(@"'", StringComparison.Ordinal) + 1).ToUpper();
            return GetUserSecurityLevel(username);
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (!AuthorizeCore(filterContext.HttpContext))
            {
                // If not authorized, redirect to the NotAuthorizedForApplication action 
                filterContext.Result = new RedirectToRouteResult(
                   new System.Web.Routing.RouteValueDictionary {
                   {"action", "NotAuthorizedForApplication"}
                }
                );
            }
        }
        private bool GetUserSecurityLevel(string username)
        {
            return true;
        }
    }
}

这是我的网络配置:

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <appSettings>
    <add key="MailServer" value="mail2.pacificdda.com" />
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <authentication mode="Windows" />
    <authorization>
      <allow users="?"/>
    </authorization>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime targetFramework="4.0"/>
    <customErrors mode="Off" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%'Microsoft.NET'Framework'v4.0.30319'aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%'Microsoft.NET'Framework64'v4.0.30319'aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
    <modules>
      <remove name="UrlRoutingModule-4.0"/>
      <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
      <remove name="Session"/>
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      <remove name="BundleModule"/>
      <add name="BundleModule" type="System.Web.Optimization.BundleModule"/>
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.0.0" newVersion="5.2.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <connectionStrings>
     </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
</configuration>

我看到过类似于我的帖子,但我尝试过常见的东西,无法使它们在本地主机和服务器上都工作。

httpContext.User.Identity.Name Coming back as " "

检查配置文件中的授权元素。

<authorization>
  <allow users="?"/>
</authorization>

这就是告诉你的网站允许匿名用户。应该是:

<authorization>
  <deny users="?"/>
  <allow users="*"/>
</authorization>

该网站将在第一个评估为true时停止,因此如果用户是匿名的,他们将被拒绝访问,否则他们将被允许访问。

编辑

身份验证通过首先向浏览器发送指定身份验证类型的401来工作。这会提示浏览器请求凭据。web.config中的授权节点或控制器上的授权属性是促使这种情况发生的原因。如果您的web.config设置为允许匿名用户,则没有401。如果没有401,则不会发送凭据,并且Identity.Name将为空。

它可能在您的控制器中工作,因为您包含AuthorizeAttribute。