标签: asp.net-core-middleware

如何阅读ASP.NET Core Response.Body?

我一直在努力Response.Body从ASP.NET核心操作中获取属性,而我能够识别的唯一解决方案似乎不是最佳的.该解决方案需要Response.Body在一段MemoryStream时间内将流读取到字符串变量中,然后在发送到客户端之前将其交换回来.在下面的示例中,我试图Response.Body在自定义中间件类中获取值. Response.Body是一个在ASP.NET核心出于某种原因唯一的财产?我在这里遗漏了什么,或者这是一个疏忽/错误/设计问题?有更好的阅读方式Response.Body吗?

当前(次优)解决方案:

public class MyMiddleWare
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        using (var swapStream = new MemoryStream())
        {
            var originalResponseBody = context.Response.Body;

            context.Response.Body = swapStream;

            await _next(context);

            swapStream.Seek(0, SeekOrigin.Begin);
            string responseBody = new StreamReader(swapStream).ReadToEnd();
            swapStream.Seek(0, SeekOrigin.Begin);

            await swapStream .CopyToAsync(originalResponseBody);
            context.Response.Body = originalResponseBody;
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

尝试使用EnableRewind()的解决方案: 这仅适用于Request.Body,而不是Response.Body.这导致从而Response.Body不是实际的响应主体内容中读取空字符串. …

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

52
推荐指数
5
解决办法
3万
查看次数

借助SharedResources进行ASP.NET核心本地化

您好我有关于SharedResources文件的问题.在这里的教程中看了一眼:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization,我不确定我是否正确使用它.

我应该创建一个SharedResources.cs类,但是我应该把它放在哪里,如果它是空的,或者我需要填充一些数据吗?

资源文件也一样,我应该创建一个SharedResources.da.resx文件并将所有共享字符串放在那里吗?它应该去哪里?

当我使用时IHtmlLocalizer<SharedResources>,我只是编写@using并将其指向SharedResources.cs存在的命名空间?

我试图把SharedResources.csSharedResources.da.resx在资源文件夹,并用它来更改网站语言以丹麦,但它不工作.使用专用的资源文件,Index.da.resx并且IViewLocalizer工作正常,但IHtmlLocalizer<SharedResources>似乎不起作用.

当我查看链接到页面底部的示例项目时,我没有找到使用SharedResources的任何地方,如果有人用它的一个例子更新它会很棒.

这是我试图这样做的方式:

查看/主页/ Index.cshtml:

@using Funkipedia.Resources
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<Shared> SharedLocalizer
...
<p>@SharedLocalizer["Hei"]</p>
...
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中的ConfigureServices顶部:

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中的Configure顶部:

var supportedCultures = new List<CultureInfo>
{
       new CultureInfo("nb-NO"),
       new CultureInfo("sv-SE"),
       new CultureInfo("da-DK")
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
       DefaultRequestCulture = new RequestCulture("nb-NO"),
       SupportedCultures = supportedCultures,
       SupportedUICultures = supportedCultures
});
Run Code Online (Sandbox Code Playgroud)

Resources文件夹包含调用的空类Shared.cs …

asp.net asp.net-core asp.net-core-localization asp.net-core-middleware

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

究竟什么'UseAuthentication()'用于?

我有一个关于ASP.NET Core 2中的身份验证的问题:调用app.UseAuthentication()究竟是什么?

这是一个基本的先决条件,以便我可以实现我的自定义身份验证逻辑吗?我已经看过UseAuthentication的实现以及实际的中间件AuthenticationMiddleware的实现,但说实话,我不明白它实际上在做什么以及为什么它是必要的.

换句话说:

我是否需要调用UseAuthentication() 在此输入图像描述

或者它是一个很好的,我可以做我的自定义auth反正? 在此输入图像描述

如果我没有调用UseAuthentication()就好了,我仍然对AuthenticationMiddleware实际上正在做什么感兴趣.所以,如果你知道如果你能为我解释,我会非常感激.

c# authentication asp.net-core-middleware asp.net-core-2.0

27
推荐指数
2
解决办法
1万
查看次数

在ASP.Net Core中请求内容解压缩

我有时需要将更大的JSON请求有效负载发布到我的ASP.Net核心控制器.有效载荷的大小保证(至少在我看来)压缩它.由于ASP.Net核心控制器似乎不支持开箱即用的压缩请求内容,因此我推出了自己的中间件.

实现这个是微不足道的,我不确定我是否在这里遗漏了一些东西.要么是因为有一种内置的方法来实现这一目标,要么是因为我从安全性或性能角度出现了一些重大错误?

public class GzipRequestContentEncodingMiddleware
{
    public GzipRequestContentEncodingMiddleware(RequestDelegate next)
    {
        if (next == null)
            throw new ArgumentNullException(nameof(next));

        this.next = next;
    }

    private readonly RequestDelegate next;
    private const string ContentEncodingHeader = "Content-Encoding";
    private const string ContentEncodingGzip = "gzip";
    private const string ContentEncodingDeflate = "deflate";

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Headers.Keys.Contains(ContentEncodingHeader) &&
            (context.Request.Headers[ContentEncodingHeader] == ContentEncodingGzip || 
            context.Request.Headers[ContentEncodingHeader] == ContentEncodingDeflate))
        {
            var contentEncoding = context.Request.Headers[ContentEncodingHeader];
            context.Request.Headers.Remove(ContentEncodingHeader);

            var destination = new MemoryStream();

            using (var decompressor = contentEncoding == ContentEncodingGzip
                ? (Stream) new …
Run Code Online (Sandbox Code Playgroud)

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

24
推荐指数
2
解决办法
2617
查看次数

如何在asp.net核心中间件中进行DI?

我试图将依赖注入我的中间件构造函数,如下所示

public class CreateCompanyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly UserManager<ApplicationUser> _userManager;

    public CreateCompanyMiddleware(RequestDelegate next
        , UserManager<ApplicationUser> userManager
        )
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await _next.Invoke(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Startup.cs文件看起来像

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("IdentityConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    ...

    app.UseMiddleware<CreateCompanyMiddleware>();

    ...
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误

启动应用程序时发生错误.InvalidOperationException:无法从根提供程序解析作用域服务'Microsoft.AspNetCore.Identity.UserManager`1 [Common.Models.ApplicationUser]'.Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型serviceType,IServiceScope范围,IServiceScope rootScope)

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

23
推荐指数
2
解决办法
9207
查看次数

如何使用中间件删除服务器头?

在ASP.NET Core 1.0中,每个响应都将包含标头Server: Kestrel.我想删除此标头以及其他标头,如X-Power-By使用中间件.

我知道我们可以通过设置以下内容来删除主机配置中的Kestrel标头,但我想使用中间件(实际上当我们有Httpmodule时我们可以这样做,所以我学习同样的事情).我试了一下它没用.

new WebHostBuilder()
    .UseKestrel(c => c.AddServerHeader = false)
Run Code Online (Sandbox Code Playgroud)

试过的代码:

public class HeaderRemoverMiddleware
{
    private readonly RequestDelegate _next;
    public HeaderRemoverMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.OnStarting(callback: removeHeaders, state: httpContext);
        await _next.Invoke(httpContext);
    }

    private Task removeHeaders(object context)
    {
        var httpContext = (HttpContext)context;
        if (httpContext.Response.Headers.ContainsKey("Server"))
        {
            httpContext.Response.Headers.Remove("Server");
        }
        return Task.FromResult(0);
    }
}

public static class HeaderRemoverExtensions
{
    public static IApplicationBuilder UseServerHeaderRemover(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HeaderRemoverMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

.net-core asp.net-core asp.net-core-1.0 asp.net-core-middleware

14
推荐指数
1
解决办法
5126
查看次数

使用Asp.Net核心中间件将非WWW重定向到WWW

在ASP.Net核心应用程序启动我有:

RewriteOptions rewriteOptions = new RewriteOptions(); 

rewriteOptions.AddRedirectToHttps();

applicationBuilder.UseRewriter(rewriteOptions);
Run Code Online (Sandbox Code Playgroud)

在生产中我需要将所有非WWW重定向到WWW Urls

例如:

domain.com/about > www.domain.com/about
Run Code Online (Sandbox Code Playgroud)

我怎么能用Rewrite Middleware做到这一点?

我认为这可以使用AddRedirect和Regex完成:

Github - ASP.NET核心重定向文档

但不知道怎么做......

regex url-rewriting asp.net-core asp.net-core-middleware

14
推荐指数
4
解决办法
2604
查看次数

如何自定义ASP.Net Core模型绑定错误?

我想从Web API(Asp.net Core 2.1)中仅返回标准化的错误响应,但我似乎无法弄清楚如何处理模型绑定错误.

该项目只是从"ASP.NET Core Web Application">"API"模板创建的.我有一个简单的动作定义为:

[Route("[controller]")]
[ApiController]
public class MyTestController : ControllerBase
{
    [HttpGet("{id}")]
    public ActionResult<TestModel> Get(Guid id)
    {
        return new TestModel() { Greeting = "Hello World!" };
    }
}

public class TestModel
{
    public string Greeting { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用无效的Guid(例如https://localhost:44303/MyTest/asdf)向此操作发出请求,我会收到以下响应:

{
    "id": [
        "The value 'asdf' is not valid."
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有以下代码Startup.Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    JsonErrorMiddleware.CreateSingleton(env);

    if (!env.IsDevelopment())
    {
        app.UseHsts();
    }

    app
        .UseHttpsRedirection()
        .UseStatusCodePages(async ctx => …
Run Code Online (Sandbox Code Playgroud)

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

13
推荐指数
1
解决办法
5212
查看次数

Azure 函数中间件:如何返回自定义 HTTP 响应?

我正在探索运行在 Azure Function 上的内容.net 5,并发现了新的中间件功能

我构建了一个像这样的虚拟中间件:

public sealed class ExceptionLoggingMiddleware : IFunctionsWorkerMiddleware
{
    private readonly ILogger<ExceptionLoggingMiddleware> m_logger;

    public ExceptionLoggingMiddleware(ILogger<ExceptionLoggingMiddleware> logger)
    {
        m_logger = logger;
    }

    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception unhandledException)
        {
            m_logger.LogCritical(unhandledException, "Unhandled exception caught: {UnhandledException}", unhandledException.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的用例中,Azure 函数是一个 HTTP 触发函数:

public sealed class StorageAccountsFunction
{
    private readonly ILogger<StorageAccountsFunction> m_logger;

    public StorageAccountsFunction
    (
        ILogger<StorageAccountsFunction> logger
    )
    {
        m_logger = logger;
    }

    [Function("v1-post-storage-account")] …
Run Code Online (Sandbox Code Playgroud)

c# azure azure-functions asp.net-core-middleware .net-5

13
推荐指数
2
解决办法
1万
查看次数

JwtBearerMiddleware的自定义令牌位置

我们有一个调用客户端请求我们的系统没有将Bearer令牌放在标准位置('Authorization'标题)我想创建一个自定义处理程序,在正确的位置查找JWT.除了分支JwtBearerMiddleware实现是否有任何更清洁的方式我可以告诉中间件使用什么处理程序?

更简单的选择是通过在JWT中间件运行之前将JWT注入请求管道中的正确位置(请求头)来重写请求.但这似乎有点hacky.

.net asp.net-authorization jwt asp.net-core asp.net-core-middleware

12
推荐指数
1
解决办法
1618
查看次数