asp.net-core-middleware

How to do DI in asp.net core middleware?

∥☆過路亽.° 提交于 2019-12-03 04:34:56
I am trying to inject dependency into my middleware constructor as follows 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); } } My Startup.cs file looks like public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration

Read JSON post data in ASP.Net Core MVC

纵然是瞬间 提交于 2019-11-30 18:11:17
I've tried to find a solution for this, but all the ones coming up are for previous versions of ASP.Net. I'm working with the JWT authentication middleware and have the following method: private async Task GenerateToken(HttpContext context) { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; //Remainder of login code } This gets the sent data as if it was form data, but my Angular 2 front end is sending the data as JSON. login(username: string, password: string): Observable<boolean> { let headers = new Headers({ 'Content-Type': 'application/json'

ASP.NET Core Localization with help of SharedResources

你离开我真会死。 提交于 2019-11-29 22:17:52
Hi I have a question about the SharedResources file. It is glanced over in the tutorial here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization , and I'm not sure if I get it correctly. I am supposed to create a SharedResources.cs class, but where should i put it and should it be empty or do I need to fill it with some data? Same goes for the resource file, should I create a SharedResources.da.resx file and put all my shared strings there? Where should it go? And when I use IHtmlLocalizer<SharedResources> do I just write @using and point it to the namespace where

Intercept asp.net core Authorize action to perform custom action upon successful authorization

亡梦爱人 提交于 2019-11-29 15:42:22
I have an [Authorize] attribute on my web app controller so any endpoints hit ensure user is re-directed to login on OAuth server first (if not already logged in.) I now want to start writing user claims to the web app db every time a user logs in. To do this I need to have some code that runs on the web app every time a user is successfully logged in / authorised. I have been given a clue that it involves adding custom middleware. My Startup ConfigureServices code is currently as follows: public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment env) {

How to get User at Service Layer

走远了吗. 提交于 2019-11-29 13:45:33
I use ASP.NET Core 2.1 and would like to fetch User at a service level . I've seen examples when HttpContextAccessor gets injected into some service and then we fetch the current User via UserManager var user = await _userManager.GetUserAsync(accessor.HttpContext.User); or in controller var user = await _userManager.GetUserAsync(User); Problems: Injecting HttpContextAccessor into service seems to be wrong - simply because we violate SRP and the Service Layer isn't isolated (it is dependant on http context ). We can of course fetch user in a controller (a somewhat better approach), but we face

ASP NET Core modify/substitute a request body

孤者浪人 提交于 2019-11-29 13:25:28
I need to do the substitution of HttpContext.Request.Body. I've tried to do it inside middleware 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<DataSourceRequest>(originalBody); } catch { await _next.Invoke(context); } if (dataSource != null && dataSource.Take > 2000) { dataSource.Take = 2000; var bytesToWrite = dataSource.AsByteArray(); await context.Request.Body.WriteAsync

Redirect Non WWW to WWW using Asp.Net Core Middleware

我只是一个虾纸丫 提交于 2019-11-29 09:20:01
On an ASP.Net Core application startup I have: RewriteOptions rewriteOptions = new RewriteOptions(); rewriteOptions.AddRedirectToHttps(); applicationBuilder.UseRewriter(rewriteOptions); When in Production I need to redirect all Non WWW to WWW Urls For example: domain.com/about > www.domain.com/about How can I do this using Rewrite Middleware? I think this can be done using AddRedirect and Regex: Github - ASP.NET Core Redirect Docs But not sure how to do it ... A reusable alternative would be to create a custom rewrite rule and a corresponsing extension method to add the rule to the rewrite

asp.net core defaultProxy

拜拜、爱过 提交于 2019-11-28 20:51:38
In net 4.5 we are working with proxy like this: <system.net> <!-- --> <defaultProxy enabled="true" useDefaultCredentials="false"> <proxy usesystemdefault="True" proxyaddress="http://192.168.1.1:8888" bypassonlocal="True" autoDetect="False" /> <module type="CommonLibrary.Proxy.MyProxy, CommonLibrary, Version=1.0.0.0, Culture=neutral" /> </defaultProxy> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> <servicePointManager expect100Continue="false" /> </settings> </system.net> but in asp.net core or test we can't found a solution like the above Could someone please help me? I really

Intercept asp.net core Authorize action to perform custom action upon successful authorization

故事扮演 提交于 2019-11-28 10:36:09
问题 I have an [Authorize] attribute on my web app controller so any endpoints hit ensure user is re-directed to login on OAuth server first (if not already logged in.) I now want to start writing user claims to the web app db every time a user logs in. To do this I need to have some code that runs on the web app every time a user is successfully logged in / authorised. I have been given a clue that it involves adding custom middleware. My Startup ConfigureServices code is currently as follows:

How do I customize ASP.Net Core model binding errors?

扶醉桌前 提交于 2019-11-28 10:01:34
I would like to return only standardized error responses from my Web API (Asp.net Core 2.1), but I can't seem to figure out how to handle model binding errors. The project is just created from the "ASP.NET Core Web Application" > "API" template. I've got a simple action defined as: [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; } } If I make a request to this action with an