Tag: asp.net core middleware

如何自定义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 Get(Guid id) { return new TestModel() { Greeting = “Hello World!” }; } } public class TestModel { public string Greeting { get; set; } } 如果我使用无效的Guid请求此操作(例如, https://localhost:44303/MyTest/asdf ),我会收到以下响应: { “id”: [ “The value ‘asdf’ […]

如何在asp.net核心中编写中间件作为自定义路由器?

我想转换这段代码: var trackPackageRouteHandler = new RouteHandler(context => { var routeValues = context.GetRouteData().Values; return context.Response.WriteAsync( $”Hello! Route values: {string.Join(“, “, routeValues)}”); }); var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler); routeBuilder.MapRoute( “Track Package Route”, “package/{operation:regex(^track|create|detonate$)}/{id:int}”); routeBuilder.MapGet(“hello/{name}”, context => { var name = context.GetRouteValue(“name”); // This is the route handler when HTTP GET “hello/” matches // To match HTTP […]

asp.net核心defaultProxy

在net 4.5中,我们正在使用这样的代理: 但是在asp.net核心或测试中我们找不到像上面这样的解决方案有人可以帮帮我吗? 我非常感谢你的帮助 感谢和问候

ASP NET Core修改/替换请求体

我需要替换HttpContext.Request.Body。 我试过在中间件中做这件事 public async Task Invoke(HttpContext context) { if (context.Request.Path.Value.Contains(“DataSourceResult”)) { var originalBody = new StreamReader(context.Request.Body).ReadToEnd(); DataSourceRequest dataSource = null; try { dataSource = JsonConvert.DeserializeObject(originalBody); } catch { await _next.Invoke(context); } if (dataSource != null && dataSource.Take > 2000) { dataSource.Take = 2000; var bytesToWrite = dataSource.AsByteArray(); await context.Request.Body.WriteAsync(bytesToWrite, 0, bytesToWrite.Length); } else { var […]

在ASP.Net Core MVC中读取JSON post数据

我试图找到一个解决方案,但所有出现的都是以前版本的ASP.Net。 我正在使用JWT身份validation中间件并具有以下方法: private async Task GenerateToken(HttpContext context) { var username = context.Request.Form[“username”]; var password = context.Request.Form[“password”]; //Remainder of login code } 这会将发送的数据视为表单数据,但我的Angular 2前端将数据作为JSON发送。 login(username: string, password: string): Observable { let headers = new Headers({ ‘Content-Type’: ‘application/json’ }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify({ username: username, password: password }); return […]

拦截asp.net核心授权操作以在成功授权后执行自定义操作

我的网络应用控制器上有[授权]属性,因此任何端点命中都会确保用户首先被重定向到登录OAuth服务器(如果尚未登录)。 我现在想要在用户每次登录时开始将用户声明写入Web应用程序数据库。为此,我需要在每次用户成功登录/授权时在Web应用程序上运行一些代码。 我得到了一个线索,它涉及添加自定义中间件。 我的启动ConfigureServices代码目前如下: public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment env) { Configuration = configuration; Env = env; } public IHostingEnvironment Env { get; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Adds a default in-memory implementation of IDistributedCache. services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.HttpOnly = true; }); […]

如何在服务层获取用户

我使用ASP.NET Core 2.1并希望在服务级别获取User 。 我看到HttpContextAccessor被注入某个服务然后我们通过UserManager获取当前User例子 var user = await _userManager.GetUserAsync(accessor.HttpContext.User); 或在控制器中 var user = await _userManager.GetUserAsync(User); 问题: 将HttpContextAccessor注入服务似乎是错误的 – 仅仅因为我们违反了SRP并且服务层没有被隔离(它依赖于http上下文 )。 我们当然可以在控制器中获取用户 (一种更好的方法),但我们面临两难 – 我们根本不想在每个服务方法中将User作为参数传递 我花了几个小时思考如何最好地实现它,并提出了一个解决方案。 我不完全确定我的方法是否足够,并且不违反任何软件设计原则。 共享我的代码希望从StackOverflow社区获得建议。 这个想法如下: 首先,我介绍注册为Singleton的SessionProvider 。 services.AddSingleton(); SessionProvider有一个Session属性,用于保存User , Tenant等。 其次,我介绍SessionMiddleware并注册它 app.UseMiddleware(); 在Invoke方法中,我解析了HttpContext , SessionProvider和UserManager 。 我取了User 然后我初始化ServiceProvider单例的Session属性: sessionProvider.Initialise(user); 在此阶段, ServiceProvider具有包含我们需要的信息的Session对象。 现在我们将SessionProvider注入到任何服务中,并且其Session对象已准备好使用。 码: SessionProvider : public class SessionProvider { public […]

exception处理中间件和页面

我是中间件概念的新手,我目前正在努力处理我的MVC Core项目中的exception。 我想要发生的是捕获,记录exception,然后将用户发送到带有消息的友好错误页面。 起初,我试图在中间件中管理所有这些,但意识到我可能没有正确地做到这一点。 因此,如果我想要这个流程发生,我应该使用我的exception日志记录中间件和app.UseExceptionHandler(“/ Error”),以便中间件重新抛出exception到页面? 如果是这样,我如何在错误页面中获取exception详细信息? 我想首先拦截的exception处理机制应该是Configure中的最后一个吗?这是正确的吗? 我发现的所有示例都严格处理HTTP状态代码错误,如404; 我正在寻找处理实际的exception(及其子类)。 这样,在我的View页面中,我可以在适用的情况下抛出自己的exception(例如,如果为必填字段提供了一个null。) Startup.cs片段: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, LoanDbContext context) { loggerFactory.AddConsole(Configuration.GetSection(“Logging”)); loggerFactory.AddDebug(); app.UseStatusCodePages(); if (env.IsDevelopment() || env.IsEnvironment(“qa”)) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler(“/Error”); } app.UseMiddleware(loggerFactory); // … rest of Configure is irrelevant to this issue MyExceptionHandler.cs using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using […]

ASP.NET核心JWT承载令牌自定义validation

经过大量阅读,我找到了一种实现自定义JWT承载令牌validation器的方法,如下所示。 Starup.cs代码: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) { loggerFactory.AddConsole(Configuration.GetSection(“Logging”)); loggerFactory.AddDebug(); app.UseStaticFiles(); app.UseIdentity(); ConfigureAuth(app); app.UseMvcWithDefaultRoute(); } private void ConfigureAuth(IApplicationBuilder app) { var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection(“TokenAuthentication:SecretKey”).Value)); var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim […]

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

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