小编Hen*_*ema的帖子

OWIN中间件被调用的次数比预期的多,我还缺少什么?

我正在测试OWIN中间件,并编写了以下中间件类。但是奇怪的是,当我请求没有任何路径(localhost:<port>)的URL时,我总共调用此中间件大约四次。但是,当我打电话localhost:<port>/welcome.htm或我打电话时,localhost:<port>/default.htm它仅被调用一次,如预期的那样。我想念什么?

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        await this.Next.Invoke(context);

        if (context.Request.Path.HasValue && (context.Request.Path.Value == "/" || context.Request.Path.Value.EndsWith(".htm")))
        {
            using (var writer = new StreamWriter(context.Response.Body))
            {
                await writer.WriteLineAsync("Next middleware: " + this.Next.ToString());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的启动配置:

    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.UseErrorPage(new ErrorPageOptions {
            ShowCookies = true,
            ShowEnvironment = true,
            ShowExceptionDetails = true,
            ShowHeaders = true,
            ShowQuery = true,
            ShowSourceCode …
Run Code Online (Sandbox Code Playgroud)

iis owin katana

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

在ASP.NET 5中动态加载程序集

我曾经有一些代码扫描了bin我的应用程序的目录,但尚未加载到AppDomain中的程序集并加载它们.它基本上看起来像:

foreach (var assemblyPath in Directory.GetFiles("path\to\bin", "*.dll"))
{
    var inspected = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
    Assembly.Load(inspected.GetName());
}
Run Code Online (Sandbox Code Playgroud)

为简洁起见,我跳过了try/catch子句等.

这允许我在运行时删除bin文件夹中的程序集以及某些接口的实现,并让IoC容器自动拾取它们.现在有了新的Roslyn魔法,在调试时就不再有物理DLL了.有没有办法动态检索程序集名称,项目名称或依赖项名称(in project.json).

我想我必须在Entropy repo中实现类似这个例子的东西,但我不知道如何为我的场景实现它.

c# c#-6.0 asp.net-core

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

访问ConfigureServices中的IApplicationEnvironment

在我的ConfigureServices方法中,我想读取一个文件(在我的例子中是用于签署令牌的证书,但它可以是设置服务所需的任何文件).因此我需要知道ApplicationBasePath来自IApplicationEnvironment.

目前我通过获取这样的IApplicationEnvironment服务来解决问题:

public void ConfigureServices(IServiceCollection services)
{
    ...
    string basePath;
    var serviceProvider = services.BuildServiceProvider();
    try
    {
        basePath = serviceProvider.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath;
    }
    finally
    {
        (serviceProvider as IDisposable)?.Dispose();
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

这种方法有效,但我不确定这是否是正确的方法.所以我的问题是:

  1. 有没有更好的方法来读取文件ConfigureServices
  2. 是否有更好的方法来获取应用程序基础路径ConfigureServices
  3. 如果我的方法是正确的,我能IDisposable正确处理吗?

c# asp.net-core

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

从自定义中间件调用控制器和操作

我是ASP.NET 5和中间件类的新手.我正在尝试创建的是一个中间件类,它读取传入的URL请求.基于此,我要么让它通过并进行正常的路由查找,或者我希望我的中间件类从我的Web API类调用特定的控制器/操作.

我现在拥有的是以下内容.我认为代码中的注释解释了我想要实现的目标.

public class RouteMiddleware
{
    private readonly RequestDelegate _next;

    public RouteMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if(httpContext.Request.QueryString.Value == "test")
        {
            // Call custom Controller / Action
            // Then, don't do any more route resolving, since we already have the right controller/action
        }
        else
        {
            // Continue like normal
            await _next.Invoke(httpContext);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在我的中间件类中执行此操作?

c# middleware asp.net-core-mvc asp.net-core

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

ASP.NET 5 中 System.Web.Mvc.Html.InputExtensions 的等效项是什么?

ASP.NET 5 与System.Web.Mvc.Html.InputExtensionsASP.NET 4 中使用的等效项是什么?

请参阅下面的示例:

public static class CustomHelpers
{
    // Submit Button Helper
    public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)
    {
        string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
        return new MvcHtmlString(str);
    }

    // Readonly Strongly-Typed TextBox Helper
    public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool isReadonly)
    {
        MvcHtmlString html = default(MvcHtmlString);

        if (isReadonly)
        {
            html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
                expression, new { @class = "readOnly",
                @readonly = "read-only" });
        } …
Run Code Online (Sandbox Code Playgroud)

c# html-helper asp.net-core-mvc asp.net-core

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

如何在ASP.NET Core中使用IApplicationBuilder中间件重载

ASP.NET Core为app.Use()方法提供了两个重载。通常我们只使用一个重载

app.Use(Func<HttpContext,Func<Task>, Task> middleware)
Run Code Online (Sandbox Code Playgroud)

用作

app.Use(async (context, next) => {
    await context.Response.WriteAsync("1st middleware <br/>");
    await next.Invoke();
});
Run Code Online (Sandbox Code Playgroud)

我要使用的另一个重载是

app.Use(Func<RequestDelegate,RequestDelegate> middleware)
Run Code Online (Sandbox Code Playgroud)

我找不到如何使用此重载的示例。任何想法都会很棒。

c# middleware asp.net-core-mvc asp.net-core-middleware

4
推荐指数
1
解决办法
1624
查看次数

MvcOptions.InputFormatters不适用于asp.net vnext beta7

我的应用程序在迁移到beta 6/7之后停止工作,在调查之后,我发现我的json反序列化器不再使用(Jil),它被要求写入而不是用于阅读.

现在已经3天了,我正在搜索论坛并阅读aspnet代码,但我还没有找到问题.

我注意到JSON.net在beta 6中无处不在,在beta 7中稍微少一点.

这是我的代码:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore(options =>
        {
            var jilFormatter = new JilMediaTypeFormatter();
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(jilFormatter);
            options.InputFormatters.Clear();
            options.InputFormatters.Add(jilFormatter);

            options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));

            options.ModelBinders.Add(new DocumentModelBinder());
            options.ModelBinders.Add(new DataTablesBinder());
        });
        services.AddDataProtection();
        services.AddWebEncoders();

    }
Run Code Online (Sandbox Code Playgroud)

即使我只是在没有添加对象的情况下执行InputFormatters.Clear(),它也会对请求进行反序列化,我不知道它是如何做到的.

我的JIL InputFormatter/OutputFormatter(ouputformatter工作,我可以在CanWrite中断,但CanRead没有任何反应)

internal class JilMediaTypeFormatter : IOutputFormatter, IInputFormatter
{
    private static readonly string [] _readableTypes = new[] { "application/json", "text/json", "text/javascript" };
    private static readonly Task<bool> _done = Task.FromResult(true);

    private readonly Options _options = Options.RFC1123ExcludeNullsIncludeInherited;


    public bool CanWriteResult(OutputFormatterContext context, Microsoft.Net.Http.Headers.MediaTypeHeaderValue contentType)
    {
        return contentType ==null …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core

3
推荐指数
1
解决办法
805
查看次数

运行时服务不再注入DNX控制台应用程序(RC1)

我曾经能够将运行时服务注入IApplicationEnvironmentPogramDNX控制台应用程序类的构造函数中.但是,使用RC1的最新CI版本,服务不再被注入:

public Program(IApplicationEnvironment env)
{
    if (env == null)
    {
        // env is null.
        throw new ArgumentNullException(nameof(env));
    }
}
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection dnx asp.net-core

3
推荐指数
1
解决办法
1150
查看次数

string.Join奇怪的行为

我试图string.Join使用以下参数调用(第一个参数是分隔符):

string.Join(";", null, "string", 0); //returns empty string ???.
string.Join(";", null, null, 0); //returns empty string ???.
string.Join(";", null, null, null); //returns ";;;" - Good
string.Join(";", 0, 0, 0); //returns "0;0;0" - Good
string.Join(";", 0, null, 0); // "0;;0" - Good
string.Join(";", null, 0, null); // empty
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么它这样做?如何依赖string.Join在这种情况下?

.net c# string

3
推荐指数
1
解决办法
94
查看次数

配置绑定不起作用

我有以下设置:

{
  "AppSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "Database": "local",
    "ValidOrigins": [ "http://localhost:61229" ]
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我做绑定:

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Run Code Online (Sandbox Code Playgroud)

我有以下设置文件:


    public class AppSettings
    {
        public string ConnectionString = "";
        public string Database = "";

        public List<string> ValidOrigins { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

做绑定:

    AppSettings settings = new AppSettings();
    Configuration.GetSection("AppSettings").Bind(settings);
Run Code Online (Sandbox Code Playgroud)

settings.ValidOrigins是确定的,但ConnectionStringDatabasenull.我究竟做错了什么?

c# configuration asp.net-core

3
推荐指数
1
解决办法
1071
查看次数