GVKun编程网logo

asp.net-mvc – 城堡PerRequestLifestyle无法识别

16

对于asp.net-mvc–城堡PerRequestLifestyle无法识别感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于.NETCoreMVCRequestLocalization忽略De

对于asp.net-mvc – 城堡PerRequestLifestyle无法识别感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于.NET Core MVC RequestLocalization忽略DefaultRequestCulture、.net – 什么是System.Web.Mvc.MvcHandler.ProcessAsyncRequest()?、asp.net core 5 Request.Schema 无法识别正确的命名空间、ASP.NET MVC中的asp.net-mvc – 文件大小上传限制:web.config中的超过1个maxRequestLength设置的有用信息。

本文目录一览:

asp.net-mvc – 城堡PerRequestLifestyle无法识别

asp.net-mvc – 城堡PerRequestLifestyle无法识别

Castle / Windsor新手,请耐心等待.

我目前正在使用框架System.Web.Mvc.Extensibility并在其启动代码中,它注册了HttpContextBase,如下所示:

container.Register(Component.For<HttpContextBase>().LifeStyle.Transient.UsingFactoryMethod(() => new HttpContextwrapper(HttpContext.Current)));

我想要做的是改变行为并将httpContextBase的生活方式改为PerWebRequest.

所以我将代码更改为以下内容:

container.Register(Component.For<HttpContextBase>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => new HttpContextwrapper(HttpContext.Current)));

但是,当我这样做时,我收到以下错误:

System.Configuration.ConfigurationErrorsException: Looks like you forgot to 
 register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
 Add '<add name="PerRequestLifestyle" 
 type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,Castle.MicroKernel" 
 />' to the <httpModules> section on your web.config

我在< system.web>下做了和< system.webServer>,但是,我仍然得到相同的错误.任何提示?

提前致谢.

更新

每个请求添加了代码块

在system.web.mvc.extensibility框架中,有一个名为extendedMvc​​Application的类,它继承自HttpApplication,在Application_start方法中,它调用BootStrapper.Execute().此方法的实现如下:

public void Execute()
    {
        bool shouldSkip = false;

        foreach (IBootstrapperTask task in ServiceLocator.GetAllInstances<IBootstrapperTask>().OrderBy(task => task.Order))
        {
            if (shouldSkip)
            {
                shouldSkip = false;
                continue;
            }

            TaskContinuation continuation = task.Execute(ServiceLocator);

            if (continuation == TaskContinuation.Break)
            {
                break;
            }

            shouldSkip = continuation == TaskContinuation.Skip;
        }
    }

如您所见,它循环遍历IBootStrapperTask列表并尝试执行它们.碰巧我有一个任务在我的mvc应用程序中注册路由:

public class RegisterRoutes : RegisterRoutesBase
{
    private HttpContextBase contextBase;

    protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator)
    {
        contextBase = serviceLocator.GetInstance<HttpContextBase>();
        return base.ExecuteCore(serviceLocator);
    }

    protected override void Register(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}",new { favicon = @"(.*/)?favicon.ico(/.*)?" });
        routes.IgnoreRoute("{*robotstxt}",new { robotstxt = @"(.*/)?robots.txt(/.*)?" });

        XmlRouting.SetAppRoutes(routes,contextBase.Server.MapPath("~/Configuration/Routes.xml"));
    }
}

你可以看到我需要getInstance(解析)一个httpcontextbase对象,这样我就可以得到一个xml文件的服务器路径.

解决方法

在撰写本文时,PerWebRequest生活方式不支持在Application_Start()中进行解析.

请参阅问题描述和讨论:

> http://support.castleproject.org/projects/IOC/issues/view/IOC-ISSUE-166
> http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e

这种特殊情况的解决方法:

>将RegisterRoutes注册为实例,将当前上下文显式传递给构造函数参数,例如:

container.Register(Component.For<IBootstrapperTask>()
                            .Instance(new RegisterRoutes(Context)));

>使用HostingEnvironment.MapPath而不是contextBase.Server.MapPath.想让它变得模糊吗?通过简单的界面使用它,例如:

interface IServerMapPath {
    string MapPath(string virtualPath);
}

class ServerMapPath: IServerMapPath {
    public string MapPath(string virtualPath) {
        return HostingEnvironment.MapPath(virtualPath);
    }
}

container.AddComponent<IServerMapPath,ServerMapPath>();

然后将IServerMapPath注入RegisterRoutes.

.NET Core MVC RequestLocalization忽略DefaultRequestCulture

.NET Core MVC RequestLocalization忽略DefaultRequestCulture

我通过以下方法为es-ES实现了具有单个MVC视图的RequestLocalization(注意:此代码仅压缩到最相关的部分):

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,opts =>
                                     {
                                         opts.ResourcesPath = "Resources";
                                     });
}


public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)
{
     var english = "en-US";
     var englishRequestCulture = new RequestCulture(culture: english,uiCulture: english);
     var supportedCultures = new List<CultureInfo>
                         {
                             new CultureInfo("en-US"),new CultureInfo("es-ES")
                         };

     var options = new RequestLocalizationoptions
            {
                DefaultRequestCulture = englishRequestCulture,SupportedCultures = supportedCultures,SupportedUICultures = supportedCultures
            };

     app.UseRequestLocalization(options);
     app.UseMvc();
}

当将culture = en-US或culture = es-ES作为查询字符串参数传递时,这非常有效.我的期望是,当没有提供文化时,默认文化应该是en-US.但是,当我不提供culture参数时,我的视图默认为es-ES.我已确认所有其他本地化提供商也默认为en-US.

我还应该注意到,我尝试通过ConfigureServices()进行本地化,但是根本无法使其正常运行:

services.Configure<RequestLocalizationoptions>(
             options =>
             {
                 var supportedCultures = new List<CultureInfo>
                     {
                         new CultureInfo("en-US"),new CultureInfo("es-ES")
                     };

                 options.DefaultRequestCulture = new RequestCulture(culture: "en-US",uiCulture: "en-US");
                 options.SupportedCultures = supportedCultures;
                 options.SupportedUICultures = supportedCultures;
             });

解决方法

我自己也有同样的问题.看看你的HTTP请求!它们是否包含设置为es-ES(或任何内容)的Accept-Language标头?然后你的本地化中间件工作正常.三个默认的RequestCultureProviders之一,即AcceptLanguageHeaderRequestCultureProvider,尝试通过执行您所做的操作来确定文化 – 查找Accept-Language标头.

所以不,正如您和之前的回答所建议的那样,本地化中间件不会忽略DefaultRequestCulture.

.net – 什么是System.Web.Mvc.MvcHandler.ProcessAsyncRequest()?

.net – 什么是System.Web.Mvc.MvcHandler.ProcessAsyncRequest()?

我正在NewRelic中进行一些跟踪,我看到几乎每个请求都包含对’System.Web.Mvc.MvcHandler.ProcessAsyncRequest()’的调用.

此函数调用可能需要300毫秒到100秒(严重的是100秒).我试图搜索msdn文档,但http://msdn.microsoft.com/en-us/library/system.web.mvc.mvchandler.aspx上没有任何内容

显然,这里有些东西在骗我.

我有一些理论说明为什么这么长时间:

>类型推断?我正在使用结构图.
>服务器资源问题?
> .net版本不兼容某种?
> asp.net mvc某种不兼容性?

环境:

.net 4

asp.net mvc 3

专用的vm

解决方法

当我发现这个问题时,我认为和@garfbradaz一样,并查看了MVC源代码.有趣的是,因为我没有发现ProcessAsyncRequest方法的引用.

因此,我认为它可能是New Relic注入的东西,或者正如你所说的那样,是一种红鲱鱼,有些东西对我们说谎!我关闭了New Relic,并与他们的支持团队联系.

今天,在收到来自New Relic团队的一位反应灵敏且彬彬有礼的成员的几封电子邮件之后,他们又回到我身边并确认这是一个错误(各种各样).以下是他们的回复:

ProcessAsyncRequest is a custom name that we use for any metric being
recorded that is not / does not inherit from “System.Web.UI.Page.”
Given that MVC view engine uses “System.Web.Mvc.ViewPage” all of those
metrics will incorrectly fall under the New Relic moniker of
“ProcessAsyncRequest.”

I will be working on a modification to the agent and the core
instrumentation that will hopefully aggregate these metrics
appropriately. I am sorry for the confusion and trouble this has
caused you.

I’ll give you an update as I get close to a solution.

编辑:下面的New Relic的进一步回复 – 看起来他们有一个修复到位.

I just pushed a commit that will help us better classify the
transactions coming from the installed agent.

As far as the performance issue we did discover an issue reported by
the awesome engineers at AppHarbor that was causing TypeLoadExceptions
which might be related to slow loading / compiling code being put into
the cache. We have found the cause and are in the final testing phases
of that fix and we are hoping to get the fix in the next release of
the agent.

来自New Relic的尼克非常出色地回应了这一点,他们的产品非常有用,所以我没有任何不好的感受,只是想我会在这里分享细节.

很高兴发现我的MVC应用程序中没有鬼魂!

现在,我对任何有这些问题的人的建议是关闭New Relic直到他们的下一个版本.

编辑2:New Relic的Nick今天通过电子邮件发送给我 – 他们最新的代理(版本2.0.9.15) – 现在已经可以使用,应该可以解决这个问题.

asp.net core 5 Request.Schema 无法识别正确的命名空间

asp.net core 5 Request.Schema 无法识别正确的命名空间

如何解决asp.net core 5 Request.Schema 无法识别正确的命名空间?

我使用以下代码生成电子邮件身份验证链接(用户应单击该链接,如果该链接有效,则该帐户将被激活)。以下代码可以在控制器中正常工作,但我重构了代码并将其移至服务类。 Request.Schema 无法识别正确的命名空间。我已经尝试了几种方法和包,但它不起作用。我该如何解决?

用途:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
//using Microsoft.AspNetCore.Mvc;
using ProjectName.Core.DTOs.ClientDTOs;
using ProjectName.Core.Services.Interfaces;
using ProjectName.Core.Utilities;
using ProjectName.DataLayer.Context;
using ProjectName.DataLayer.Entities.PublicEntities;
using ProjectName.DataLayer.Entities.UserEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Web.Mvc;
using System.Threading.Tasks;

我遵循了这个 document on microsoft 但仍然无法正常工作....

网址操作

var address = Microsoft.AspNetCore.Mvc.IUrlHelper.Action(
    "ConfirmEmail","Account",new { username = newUser.UserName,token = emailConfirmationToken },**Request.Scheme**);

解决方法

首先创建一个用于编码 URL 和令牌的类。

        public class TokenUrlEncoderService
        {
            public string EncodeToken(string token)
            {
                return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));
            }
            public string DecodeToken(string urlToken)
            {
                return Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(urlToken));
            }
        }

然后像这样在您的服务层中创建一个类。

 public class IdentityEmailService
        {
            public IdentityEmailService(IEmailSender sender,UserManager<IdentityUser> userMgr,IHttpContextAccessor contextAccessor,LinkGenerator generator,TokenUrlEncoderService encoder)
            {
                EmailSender = sender;
                UserManager = userMgr;
                ContextAccessor = contextAccessor;
                LinkGenerator = generator;
                TokenEncoder = encoder;
            }
            public IEmailSender EmailSender { get; set; }
            public UserManager<IdentityUser> UserManager { get; set; }
            public IHttpContextAccessor ContextAccessor { get; set; }
            public LinkGenerator LinkGenerator { get; set; }
            public TokenUrlEncoderService TokenEncoder { get; set; }
            private string GetUrl(string emailAddress,string token,string page)
            {
                string safeToken = TokenEncoder.EncodeToken(token);
                return LinkGenerator.GetUriByPage(ContextAccessor.HttpContext,page,null,new { email = emailAddress,token = safeToken });
            }
        }

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-5.0#use-httpcontext-from-custom-components

,

以下代码可以在控制器中正常工作,但我重构了代码并将其移至服务类。

[ { "id": "655881699304931368","username": "KASKUSTTV","apiKey": "5WA7G5LUYPJB8RII64RE443EFTTY-PY" },{ "id": "285104348274884628","username": "TEST USERNAME","apiKey": "5WA8G5LUYPJB8RII64RE443EFTTY-PY" } ] 此处是 Request 类中的属性,您的服务类必须继承自 ControllerBase 或 Controller。

更改您的代码,如下所示:

ControllerBase

请务必注册如下服务:

public interface IGenerateUrl
{
    string GetUrl();
}
public class GernateUrl : IGenerateUrl
{
    private readonly IUrlHelper url;
    public GernateUrl(IUrlHelper url)
    {
        this.url = url;
    }
    public string GetUrl()
    {
        string scheme = url.ActionContext.HttpContext.Request.Scheme;
        var address = url.Action(
        "ConfirmEmail","Account",new { username = "user",token = "token" },scheme);
        return address;
    }
}

ASP.NET MVC中的asp.net-mvc – 文件大小上传限制:web.config中的超过1个maxRequestLength设置

ASP.NET MVC中的asp.net-mvc – 文件大小上传限制:web.config中的超过1个maxRequestLength设置

我想为maxRequestLength设置多于1个设置 – 文件大小上传限制(例如一个用于File / New,另一个用于Picture / New)。我的所有操作都采取额外的参数(例如/ File / New?folderId = 234)。

单一设置按预期工作:

<httpRuntime executionTimeout="60" maxRequestLength="1024" />

我试图在根web.config中有2个位置部分的设置,但没有任何成功。我不知道在“路径” – 视图的物理aspx页面或控制器操作中写什么…但是,似乎没有任何效果。

<location path="/File/">
    <system.web>
        <httpRuntime executionTimeout="60" maxRequestLength="4096" />
    </system.web>
</location>
<location path="/Picture/">
    <system.web>
        <httpRuntime executionTimeout="60" maxRequestLength="1024" />
    </system.web>
</location>

我试图将另一个web.config放在一个特定的视图文件夹(例如/ Views / Picture / …)中,就像它在经典的Webform ASP.NET中工作一样,但这似乎也不是窍门…

<location path="">
    <system.web>
        <httpRuntime executionTimeout="60" maxRequestLength="1024" />
    </system.web>
</location>

无论我做什么,只应用httpRuntime.maxRequestLength的一个值 – 在(root)web.config … system.web中。

解决方法

看到我的回答: ASP.NET MVC and httpRuntime executionTimeout

我们今天的关于asp.net-mvc – 城堡PerRequestLifestyle无法识别的分享就到这里,谢谢您的阅读,如果想了解更多关于.NET Core MVC RequestLocalization忽略DefaultRequestCulture、.net – 什么是System.Web.Mvc.MvcHandler.ProcessAsyncRequest()?、asp.net core 5 Request.Schema 无法识别正确的命名空间、ASP.NET MVC中的asp.net-mvc – 文件大小上传限制:web.config中的超过1个maxRequestLength设置的相关信息,可以在本站进行搜索。

本文标签: