小编Nic*_*cht的帖子

MVC SessionStateAttribute不作为全局属性

如何在MVC3中将SessionStateAttribute设置为全局过滤器?在我的Global.asax中,我在RegisterGlobalFilters方法中有这个.

filters.Add(new SessionStateAttribute(SessionStateBehavior.Disabled));
Run Code Online (Sandbox Code Playgroud)

在我的家庭控制器中,我有这个.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        Session["Blend"] = "Will it blend?";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,它仍然允许我使用Session.但是,如果我使用该属性修饰HomeController类本身,我在使用Session关于Object引用为null的行上会出现错误,如果从未创建Session,我猜这是错误的吗?

我开始怀疑我的项目是否有问题.我已经得到这样一个标准的行为是有点问题,应该只是工作.

其他人有这样的问题吗?

session attributes session-state asp.net-mvc-3

6
推荐指数
1
解决办法
1395
查看次数

在VS2010和2012中发布向导错误

我一直在使用VS2010中的发布向导来部署我的MVC应用程序,我没有遇到任何问题,但间歇性地发布将失败并出现以下错误.

错误23 Web部署任务失败.(无法完成对远程代理URL'https:// webserver:8172/msdeploy.axd?site = mysite'的请求.)

无法完成对远程代理URL'https:// webserver:8172/msdeploy.axd?site = mysite'的请求.请求已中止:请求已取消.无法使用已与其基础RCW分离的COM对象.

这似乎是随机发生但是我开VS的时间越长越有可能发生它并且保证修复它的方法是重启VS但是如果我让VS长时间打开(全天或者一夜之间开始变得非常沮丧,每次发生时都要重启VS. 老实说,我不记得错误号码是否总是23,我会在下次发生的时候寻找它,但是有其他人有这个问题或者知道可能是什么原因引起的吗?

更新: 使用VS2012时仍然存在问题.

visual-studio-2010 webdeploy microsoft-web-deploy visual-studio-2012

6
推荐指数
1
解决办法
2794
查看次数

使用StructureMap3在MVC应用程序中依赖注入当前用户

我有一个现有的应用程序使用2.x版本的Structuremap中的最后一个版本,它工作正常.StructureMap 3刚刚上线,我决定尝试更新它,看看它是怎么回事.

但无论我做什么,我似乎无法正确解决当前用户.我不确定它是否试图在应用程序的生命周期中过早地构建依赖项或者交易可能是什么.因为最近的发布,几乎没有任何信息,我发现它还没有任何用处.

注册依赖项的行.

For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
For<ICurrentUser>().HybridHttpOrThreadLocalScoped().Use(x => GetCurrentUser(x));
Run Code Online (Sandbox Code Playgroud)

我解决依赖关系的方法

    private ICurrentUser GetCurrentUser(IContext context)
    {
        try
        {
            var httpContext = context.GetInstance<HttpContextBase>();
            if (httpContext == null) return null;
            if (httpContext.User == null) return null;
            var user = httpContext.User;
            if (!user.Identity.IsAuthenticated) return null;

            var personId = user.GetIdentityId().GetValueOrDefault();
            return new CurrentUser(personId, user.Identity.Name);
        }
        catch (Exception ex)
        {
            context.GetInstance<ILogger>().Error("Error trying to determine the current user.", ex);
            throw new Exception("Error trying to determine the current user.", ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的ICurrentUser接口

public interface ICurrentUser …
Run Code Online (Sandbox Code Playgroud)

structuremap asp.net structuremap3

6
推荐指数
1
解决办法
834
查看次数

使用.net core 2.0的组件库进行Angular 4预渲染

据我所知,在预渲染角度应用程序时,任何依赖于窗口或文档的组件库都无法使用.

这是否意味着在不编写我们自己的组件库并使其不依赖于窗口的情况下预渲染应用程序几乎是不可能的?如果有一种友好的方式,那么人们就已经做到了,对吧?

这就引出了一个问题:在成功预渲染角度应用程序并使用外部组件库时,人们遵循了哪些策略?如果没有办法做到这一点,人们是否使用预渲染而没有任何这样的库?

我已经完成了所有可能的解决方案,使角度材料与aspnetcore 2.0预渲染一起工作,但它们都没有工作,例如:angular-ssr

任何类型的策略建议都非常受欢迎,这也让我想知道预呈现是否会如此痛苦,对于应用程序的业务方面非常重要,使用react是一种更好的策略?

angular-universal asp.net-core-mvc-2.0

6
推荐指数
0
解决办法
96
查看次数

未找到部分视图时故障转移到备用视图?

我有一个MVC应用程序,它使用从父对象类型继承的动态业务对象.例如,基类Client可能有两个子类调用VendorServiceProvider,而这些都是由同一个控制器来处理.我有一个部分视图,我在查看客户端的详细信息时加载到页面的右侧_Aside.cshtml.当我加载客户端时,我首先尝试寻找一个特定的Aside,然后我加载了一个通用的.下面是代码的样子.

@try
{
    @Html.Partial("_" + Model.Type.TypeName + "Aside")
}
catch (InvalidOperationException ex)
{
    @Html.Partial("_Aside")
}
Run Code Online (Sandbox Code Playgroud)

TypeName属性中包含"Vendor"或"ServiceProvider".

现在这个工作正常,但问题是我只希望它在未找到视图时进行故障转移,当InvalidOperationException部分视图实际抛出时(通常是它可能调用的子操作的结果),它也会失败.我想过要检查,Exception.Message但这看起来有点hackish.有没有其他方法我可以得到所需的结果,而无需检查Message属性或这是我唯一的选择吗?

ex.Message = "The partial view '_ServiceProviderAside' was not found or no view
              engine supports the searched locations. The following locations were
              searched: (... etc)"
Run Code Online (Sandbox Code Playgroud)

更新:这是根据杰克的回答,我目前在我的项目中使用扩展方法的类,以及Chao的建议.

//For ASP.NET MVC
public static class ViewExtensionMethods
{
    public static bool PartialExists(this HtmlHelper helper, string viewName)
    {
        if (string.IsNullOrEmpty(viewName)) throw new ArgumentNullException(viewName, "View …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc partial-views viewengine razor

5
推荐指数
2
解决办法
2703
查看次数

ASP.NET MVC,CustomErrors和ResponseRewrite

我有一个MVC网站(v5,虽然我认为它不相关)我在尝试建立数据库连接时故意引入错误(连接字符串中的服务器IP错误).当用户点击HomeController时,构造函数的一个依赖项是UserRepository(获取当前用户配置文件数据),这取决于数据库连接/会话是否可用.如果不是,则依赖性解析器无法注入UserRepository,并且当发生这种情况时会导致错误(与任何控制器的任何依赖关系一样),并且我得到一个通用的"没有为此对象定义的无参数构造函数".这是没用的.

所以我正在尝试使用自定义错误页面来检索内部异常并以友好的方式显示它.(因为在尝试获取HomeController时发生此错误,它实际上从未到达HandleErrorAttribute,因此依赖于CustomErrors).

所以我有一个带有一系列动作的ErrorsController ......

来自ErrorsComtroller.cs的片段

public ActionResult Error()
{
    return View("Error_500");
}

public ActionResult NotFound()
{
    return View("Error_404");
}
Run Code Online (Sandbox Code Playgroud)

来自web.config的代码段

<customErrors mode="On">
  <error statusCode="404" redirect="~/errors/notfound" />
  <error statusCode="500" redirect="~/errors/error" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)

Error_500页面非常基本,它的模型类型为HandleErrorInfo,但如果它不存在,则使用它检查异常详细信息Server.GetLastError().问题是,GetLastError()总是为空,我得到我的自定义错误页面,但没有超出我的"意外错误发生"的一般反馈之外的其他详细信息.在做了一些挖掘后,我发现重定向后该方法不起作用,这是CustomErrors的默认方式.所以我改变了web.config来使用这一行代替......

来自web.config的代码段

这样它就不会导致重定向,并且GetLastError()应该有关于数据库连接问题的异常详细信息.事情是,现在我得到这个消息的默认ASP.NET错误页面.

处理您的请求时发生异常.此外,执行第一个异常的自定义错误页面时发生另一个异常.请求已终止.

所以我使用intellitrace进行了更多挖掘,我看到了有关数据库连接的异常.稍微向下看,我看到HomeController上没有无参数构造函数的错误,然后是一个关于在尝试创建'HomeController'类型的控制器时遇到错误的错误.但后来我看到一个人说

执行/ errors/error的子请求时出错

所以我直接导航到那条路径,页面工作正常.但是当它用于带有ResponseRewriteredirectmode的customerrors时,它会出错.我在动作的第一行(也是唯一一行)上设置了一个断行ErrorsController.Error(),但它永远不会被击中.如果我将自定义错误中的重定向路径替换为静态文件,它可以正常工作,但如果我将其更改回~/errors/error它,则会再次失败.

当指定使用MVC操作作为CustomErrors的url时是否存在问题ResponseRewrite

asp.net error-handling asp.net-mvc custom-errors

5
推荐指数
1
解决办法
1372
查看次数

nHibernate在多个线程上枚举相同的集合

我有一个生产应用程序(IIS8,MVC5,nHibernate DAL),我注意到最近的高CPU使用率.循环应用程序池修复它但在从服务器执行一些诊断和内存转储以分析问题后,我注意到多个线程的一致模式试图枚举相同的集合.最常见的一点是应用程序检查用户角色的位置.我怀疑这可能更多的是这个代码是为每个验证权限的请求运行的,所以它更可能是它被卡住的集合?

public IList<Role> GetRoles(string username)
{
    var login = GetLoginForUser(username);
    return !login.Groups.Any() ? new List<Role>() : login.Groups.SelectMany(x => x.Roles).OrderBy(x => x.DisplayName).ToList();
}
Run Code Online (Sandbox Code Playgroud)

我的CurrentUser对象有一个简单的接口,包含从依赖项解析器注入的用户的详细信息.我已经验证了UserId存在且有效,这一切都非常简单.当我看到这两个请求被挂起的转储时,我得到一个警告,多个线程正在枚举一个集合.当我检查转储中的两个线程时,我看到几乎相同的堆栈跟踪.(我已经在堆栈跟踪中重命名了一些命名空间细节,但它没有改变).两个请求中的userId(以及结果配置文件)是相同的,因此它似乎是由于两个独立的线程试图在几乎同时从数据库加载同一个对象.

堆栈跟踪在下面,但我不知道从这里去哪里以解决这个问题.

System.Collections.Generic.Dictionary`2[[System.__Canon, mscorlib],[System.Nullable`1[[System.Int32, mscorlib]], mscorlib]].FindEntry(System.__Canon)+129 
System.Collections.Generic.Dictionary`2[[System.__Canon, mscorlib],[System.Nullable`1[[System.Int32, mscorlib]], mscorlib]].TryGetValue(System.__Canon, System.Nullable`1<Int32> ByRef)+12 
NHibernate.AdoNet.ColumnNameCache.GetIndexForColumnName(System.String, NHibernate.AdoNet.ResultSetWrapper)+25 
NHibernate.AdoNet.ColumnNameCache.GetIndexForColumnName(System.String, NHibernate.AdoNet.ResultSetWrapper)+25 
NHibernate.AdoNet.ResultSetWrapper.GetOrdinal(System.String)+e 
NHibernate.AdoNet.ResultSetWrapper.GetOrdinal(System.String)+e 
NHibernate.Type.NullableType.NullSafeGet(System.Data.IDataReader, System.String)+29 
NHibernate.Type.NullableType.NullSafeGet(System.Data.IDataReader, System.String[], NHibernate.Engine.ISessionImplementor, System.Object)+16 
NHibernate.Type.NullableType.NullSafeGet(System.Data.IDataReader, System.String[], NHibernate.Engine.ISessionImplementor, System.Object)+16 
NHibernate.Persister.Collection.AbstractCollectionPersister.ReadKey(System.Data.IDataReader, System.String[], NHibernate.Engine.ISessionImplementor)+14 
NHibernate.Persister.Collection.AbstractCollectionPersister.ReadKey(System.Data.IDataReader, System.String[], NHibernate.Engine.ISessionImplementor)+14 
NHibernate.Loader.Loader.ReadCollectionElement(System.Object, System.Object, NHibernate.Persister.Collection.ICollectionPersister, NHibernate.Loader.ICollectionAliases, System.Data.IDataReader, NHibernate.Engine.ISessionImplementor)+34 
NHibernate.Loader.Loader.ReadCollectionElement(System.Object, System.Object, NHibernate.Persister.Collection.ICollectionPersister, NHibernate.Loader.ICollectionAliases, System.Data.IDataReader, NHibernate.Engine.ISessionImplementor)+34 
NHibernate.Loader.Loader.ReadCollectionElements(System.Object[], System.Data.IDataReader, NHibernate.Engine.ISessionImplementor)+d2 
NHibernate.Loader.Loader.ReadCollectionElements(System.Object[], System.Data.IDataReader, NHibernate.Engine.ISessionImplementor)+d2 
NHibernate.Loader.Loader.GetRowFromResultSet(System.Data.IDataReader, NHibernate.Engine.ISessionImplementor, NHibernate.Engine.QueryParameters, NHibernate.LockMode[], NHibernate.Engine.EntityKey, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net nhibernate asp.net-mvc multithreading

5
推荐指数
1
解决办法
868
查看次数

我如何为AspNet.Security.OpenIdConnect.Server解决''引用类型'BaseControlContext"声明.....'

我面临着奇怪的问题.我正在阅读并创建OpenID Connect server with ASOS这篇文章ASOS - AspNet.Security.OpenIdConnect.Server.

我只是创建了新的示例解决方案并添加AuthorizationProvider了OpenIdConnectServerProvider的新子类,并覆盖了虚方法i.e. ExtractAuthorizationRequest

AuthorizationProvider.cs

public class AuthorizationProvider : OpenIdConnectServerProvider
{
    public override Task ExtractAuthorizationRequest(ExtractAuthorizationRequestContext context)
    {
        // If a request_id parameter can be found in the authorization request,
        // restore the complete authorization request stored in the user session.
        if (!string.IsNullOrEmpty(context.Request.RequestId))
        {
            var payload = context.HttpContext.Session.Get(context.Request.RequestId);
            if (payload == null)
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "Invalid request: timeout expired.");
                return Task.FromResult(0);
            }
            // Restore the authorization request …
Run Code Online (Sandbox Code Playgroud)

oauth asp.net-identity openid-connect asp.net-core asp.net-core-mvc-2.0

5
推荐指数
1
解决办法
459
查看次数

无法覆盖ASPNET核心中的Kestrel RequestSizeLimit

在asp.net核心2中,添加了一个重大更改,将请求大小限制为30 mb()。

在该文章中,如果您想推翻30 mb的限制,则提供了一种解决方案。应该通过向操作添加属性来完成此操作,如下所示:

[HttpPost]
[RequestSizeLimit(100_000_000)]
public IActionResult MyAction([FromBody] MyViewModel data)
{
Run Code Online (Sandbox Code Playgroud)

当我这样做并重建项目时,在Kestrel中仍然出现以下错误:

 An unhandled exception has occurred while executing the request
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.ThrowRequestRejected(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ForContentLength.OnReadStart()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryInit()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.<ReadAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestStream.<ReadAsyncInternal>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() …
Run Code Online (Sandbox Code Playgroud)

kestrel-http-server asp.net-core asp.net-core-2.0 asp.net-core-mvc-2.0

5
推荐指数
0
解决办法
2028
查看次数

从数据库流式传输数据 - ASP.NET Core &amp; SqlDataReader.GetStream()

当我从 ASP.NET Core 站点发送大型对象时,我试图尽量减少将大型对象从数据库加载到内存中,因为我OutOfMemoryException偶尔会遇到这种情况。

我想我会流它。现在,根据我的研究,只要您CommandBehavior.SequentialAccess在命令中指定,SQL Server 就支持这一点。我想如果我要流式传输它,我最好尽可能直接流式传输它,所以我几乎将它直接从DataReaderASP.NET MVC流式传输ActionResult

但是一旦FileStreamResult(隐藏在对 的调用下File())完成执行,我该如何清理我的阅读器/命令?连接是由 DI 提供的,所以这不是问题,但我在调用GetDocumentStream().

我有一个ActionFilterAttribute在 MVC中注册的子类,因此这为我提供了一个可以调用的入口点ActionFilterAttribute.OnResultExecuted(),但是除了处理清理数据库事务和提交/回滚内容的当前逻辑之外,我完全不知道该放什么(不包括在内,因为它并不真正相关)。

有没有办法在我的DataReader/之后进行清理Command并仍然提供一个Streamto File()

public class DocumentsController : Controller
{
    private DocumentService documentService;

    public FilesController(DocumentService documentService)
    {
        this.documentService = documentService;
    }

    public IActionResult Stream(Guid id, string contentType = "application/octet-stream") // Defaults to octet-stream when unspecified
    {
        // Simple lookup by Id so that …
Run Code Online (Sandbox Code Playgroud)

c# sql-server streaming sqldatareader asp.net-core

5
推荐指数
1
解决办法
3025
查看次数