【问题标题】:httpContext.User.Identity.Name Coming back as " "httpContext.User.Identity.Name 返回为“”
【发布时间】:2014-10-02 17:06:30
【问题描述】:

我正在尝试从我的 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>

我看过与我类似的帖子,但我尝试了常见的东西,但无法让它们同时在本地主机和服务器上工作。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 httpcontext


    【解决方案1】:

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

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

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

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

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

    编辑

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

    它可能适用于您的控制器,因为您包含了 AuthorizeAttribute。

    【讨论】:

    • 我的 401.2 访问被拒绝
    • 您还必须在 IIS Express 中启用 Windows Auth,并可能注释掉一些代码。有关启用 Windows 身份验证的信息,请参阅以下帖子:stackoverflow.com/questions/4762538/… 代码是 Startup.Auth.cs 中的 app.UseCookieAuthentication
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2020-04-19
    • 2022-01-24
    • 2022-07-26
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多