Git Product home page Git Product logo

dntcommon.web.core's Introduction

DNTCommon.Web.Core

DNTCommon.Web.Core

DNTCommon.Web.Core provides common scenarios' solutions for ASP.NET Core applications.

Install via NuGet

To install DNTCommon.Web.Core, run the following command in the Package Manager Console:

Nuget

PM> Install-Package DNTCommon.Web.Core

You can also view the package page on NuGet.

Linux (and containers) support

The SkiaSharp library needs extra dependencies to work on Linux and containers. Please install the following NuGet packages:

PM> Install-Package SkiaSharp.NativeAssets.Linux.NoDependencies
PM> Install-Package HarfBuzzSharp.NativeAssets.Linux

You also need to modify your .csproj file to include some MSBuild directives that ensure the required files are in a good place. These extra steps are normally not required but seems to be some issues on how .NET loads them.

<Target Name="CopyFilesAfterPublish" AfterTargets="AfterPublish">
    <Copy SourceFiles="$(TargetDir)runtimes/linux-x64/native/libSkiaSharp.so" DestinationFolder="$([System.IO.Path]::GetFullPath('$(PublishDir)'))/bin/" />
    <Copy SourceFiles="$(TargetDir)runtimes/linux-x64/native/libHarfBuzzSharp.so" DestinationFolder="$([System.IO.Path]::GetFullPath('$(PublishDir)'))/bin/" />    
</Target>

Usage

After installing the DNTCommon.Web.Core package, to register its default providers, call services.AddDNTCommonWeb(); method in your Startup class.

using DNTCommon.Web.Core;

namespace MyWebApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDNTCommonWeb();
        }

Features

  • ActionResults

  • Caching

    • ICacheService encapsulates IMemoryCache functionalities.
    • [NoBrowserCache] action filter sets no-cache, must-revalidate, no-store headers for the current Response.
  • DependencyInjection

    • IServiceProviderExtensions creates an IServiceScope which contains an IServiceProvider used to resolve dependencies from a newly created scope and then runs an associated callback.
  • Drawing

  • Http

  • Mail

    • IWebMailService simplifies sending an email using the MailKit library. It's able to use razor based email templates.
  • ModelBinders

    • PersianDateModelBinderProvider parses an incoming Persian date and then binds it to a DateTime property automatically. To use it globally ( assuming your app only sends Persian dates to the server), Add it to MvcOptions: services.AddMvc(options => options.UsePersianDateModelBinder()) or just apply it to an specific view-model [ModelBinder(BinderType = typeof(PersianDateModelBinder))].
    • YeKeModelBinderProvider parses an incoming text and then corrects its Ye & Ke characters automatically. To use it globally, Add it to MvcOptions: services.AddMvc(options => options.UseYeKeModelBinder()) or just apply it to an specific view-model [ModelBinder(BinderType = typeof(YeKeModelBinder))].
    • ApplyCorrectYeKeFilterAttribute parses an incoming text and then corrects its Ye & Ke characters automatically. To use it globally, Add it to MvcOptions: services.AddControllersWithViews(options => options.Filters.Add(typeof(ApplyCorrectYeKeFilterAttribute))).
  • Mvc

  • Blazor

  • Schedulers

    • BackgroundQueueController A .NET Core replacement for the old HostingEnvironment.QueueBackgroundWorkItem method.
    • ScheduledTasksController DNTScheduler.Core is a lightweight ASP.NET Core's background tasks runner and scheduler. To define a new task, create a new class that implements the IScheduledTask interface. To register this new task, call services.AddDNTScheduler(); method in your Startup class. AddDNTScheduler method, adds this new task to the list of the defined tasks. Also its first parameter defines the custom logic of the running intervals of this task. It's a callback method that will be called every second and provides the utcNow value. If it returns true, the job will be executed.If you have multiple jobs at the same time, the order parameter's value indicates the order of their execution.
  • Security

    • [AjaxOnly] action filter determines whether the HttpRequest's X-Requested-With header has XMLHttpRequest value.
    • IProtectionProviderService is an encryption provider based on Microsoft.AspNetCore.DataProtection.IDataProtector. It's only useful for short-term encryption scenarios such as creating encrypted HTTP cookies.
    • IFileNameSanitizerService determines whether the requested file is safe to download to avoid Directory Traversal & File Inclusion attacks.
    • UploadFileExtensions attribute determines only selected file extensions are safe to be uploaded.
    • AllowUploadSafeFiles attribute disallows uploading dangerous files such as .aspx, web.config and .asp files.
    • AntiDosMiddleware is a rate limiter and throttling middleware for ASP.NET Core apps. To use it first add app.UseAntiDos() and services.Configure<AntiDosConfig> to Startup.cs file. Then complete the AntiDosConfig section of the appsettings.json file.
    • IAntiXssService provides a cleaning service for unsafe HTML fragments that can lead to XSS attacks based on a whitelist of allowed tags and attributes. To use it add services.Configure<AntiXssConfig> to Startup.cs file. Then complete the AntiXssConfig section of the appsettings.json file.
    • IPasswordHasherService provides a custom Pbkdf2 hashing and validating service.

dntcommon.web.core's People

Contributors

dependabot[bot] avatar engrajabi avatar hamed-shirbandi avatar pshariiati avatar vahidn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dntcommon.web.core's Issues

Download file from URL and save on user disk

Hello.
How about downloading file from URL by IDownloadService.cs on user disk.
I have a website that provides files to download but my files are on download host, i dont want to user see original download link.
How should i use your package?

string to razor page

hi i was looking at IViewRendererService in your code
is there any way to compile an string containing html tag and asp.net core tag helper to cimpiled razor view?
i searched net for solution long time i found this package that do compline string html tag to razor view but doesnt support tag helper yet
https://github.com/toddams/RazorLight

Error when using services.AddControllers()

Summary of the issue

Environment

DNTCommon.Web.Core version: 1.8.0
.NET Core SDK version: 3.1.0
IDE: Visual Studio 16.4.0 on Windows 10

Example code/Steps to reproduce:

services.AddControllers();
services.AddDNTCommonWeb()

Output:

Exception message:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'DNTCommon.Web.Core.ViewRendererService'.
Full Stack trace:
When I Use current code in startup in my Web APi project received this exception.
services.AddControllers();
services.AddDNTCommonWeb() ;
but when I Use this Code my problem is solved.
services.AddControllersWithViews();
services.AddDNTCommonWeb() ;

my project is web api and View is not used in this project.
thanks

مقادیر مناسب DurationMin و AllowedRequests در UseAntiDos

با سلام

مقادیر مناسب برای
DurationMin و AllowedRequests
چه اعدادی هستن
زمانی که
AllowedRequests
رو مثلا به 100 برای یک دقیقه تنظیم میکنم پس از بازکردن تعداد صفحات محدودی پیغام محدودیت دیسترسی رو نشون میده

AntiDosMiddleware blocks the requests out of the defined config

I use AntiDosMiddleware in my app and it seems to not work correctly.
Some times when i try to call an api from my app, i get 409 error, but that request is not out of the AllowedRequests that defined in appsettings.json !

I set AllowedRequests to 50 requests per 1 minute and some times my request blocked at 1-10 !

.NET Core 2.1
Windows Server 2012 R2
Visual Studio 2017 5.7.6

AntiDosConfig in appsettings.json:

.
.
.
    "BannedIPAddressRanges": [
      // Some samples. Remove them!
      // "192.168.0.0/255.255.255.0", // From "192.168.0.0" to "192.168.0.255"
      // "192.168.0.10 - 192.168.10.20" // From "192.168.0.10" to "192.168.10.20"
      // More samples: https://github.com/jsakamoto/ipaddressrange
    ],
    "DurationMin": 1,
    "AllowedRequests": 50,
    "ErrorMessage": "<html><head><title>Error !</title><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /></head><body><div style='border-color: gray; border-width: 1pt; border-style:solid'><div align='center' style='font-family: Tahoma; font-size: 9pt; direction: rtl; background:#B6B66B'><br /><span style='color:white'>Please come back later!</span><br /><br /></div></div></body></html>",
    "IgnoreLocalHost": true
.
.
.

DNTCommon.Web.Core.ProtectionProviderService

من وقتی یکبار پروژه رو اجرا میکنم کلید جدیدی ساخته میشه و هیچ مشکلی ندارم

اما وقتی بانک اطلاعاتی رو پاک میکنم کلید جدید ساخته میشه و کلید قبلی هنوز توی کوکی ها هست و زمانی که میخوام کوکی رو بخونم خطا صادر میشه

که توی لینک زیر قبلا خطا رو گزارش دادم

#9

آیا راهی وجود داره در صورت پاک کردن دیتابیس و ساخت مجدد آن این خطا دریافت نشه؟

یا راهی وجود داره کوکی ها رو پاک کرد؟

Sanitized html from tinymCE

Summary of the issue

Hello and thanks for sharing your knowledge,
I try to use AntiXss, Set appsetings.json the same as this project add codes in startup,
Two line for get configuration data from appseting and one for add this service ,
another hand i have a tinyMCE for get data from my blog when run my project i got the same as paste

<html>
<head>
</head>
<body><p>_antiXssService.GetSanitizedHtml("&lt;A HREF=\"http://www.codeplex.com?url=&frac14;script&frac34;alert(&cent;XSS&cent;)&frac14;/script&frac34;\"&gt;XSS&lt;/A&gt;");</p></body>
</html>

test many way: past this code(Html code) on your project but get the same as my project without remove tags

<!DOCTYPE html><html><head></head><body><div>&lt;A HREF=\"http://www.codeplex.com?url=&frac14;script&frac34;alert(&cent;XSS&cent;)&frac14;/script&frac34;\&gt;XSS&lt;/A&gt;</div></body></html>

and show return value on Mvc Page as @html.row(...) , => show orginal text with out clean text
is tahat my mistake to do something?

Environment

The in-use version:MVC core 2.2
Operating system: win 10 x64
IDE: (Visual Studio 2017)


AntiDosFirewall Error

Summary of the issue

InvalidOperationException: Cache entry must specify a value for Size when SizeLimit is set.

Error


    Microsoft.Extensions.Caching.Memory.MemoryCache.SetEntry(CacheEntry entry)
    Microsoft.Extensions.Caching.Memory.CacheEntry.Dispose()
    Microsoft.Extensions.Caching.Memory.CacheExtensions.Set<TItem>(IMemoryCache cache, object key, TItem value, DateTimeOffset absoluteExpiration)
    DNTCommon.Web.Core.MemoryCacheService.Add<T>(string cacheKey, T value, DateTimeOffset absoluteExpiration)
    DNTCommon.Web.Core.AntiDosFirewall.IsDosAttack(AntiDosFirewallRequestInfo requestInfo)
    DNTCommon.Web.Core.AntiDosFirewall.ShouldBlockClient(AntiDosFirewallRequestInfo requestInfo)
    DNTCommon.Web.Core.AntiDosMiddleware.Invoke(HttpContext context, IOptionsSnapshot<AntiDosConfig> antiDosConfig, IAntiDosFirewall antiDosFirewall)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Detail Error:

System.InvalidOperationException: Cache entry must specify a value for Size when SizeLimit is set.

   at Microsoft.Extensions.Caching.Memory.MemoryCache.SetEntry(CacheEntry entry)

   at Microsoft.Extensions.Caching.Memory.CacheEntry.Dispose()

   at Microsoft.Extensions.Caching.Memory.CacheExtensions.Set[TItem](IMemoryCache cache, Object key, TItem value, DateTimeOffset absoluteExpiration)

   at DNTCommon.Web.Core.MemoryCacheService.Add[T](String cacheKey, T value, DateTimeOffset absoluteExpiration)

   at DNTCommon.Web.Core.AntiDosFirewall.IsDosAttack(AntiDosFirewallRequestInfo requestInfo)

   at DNTCommon.Web.Core.AntiDosFirewall.ShouldBlockClient(AntiDosFirewallRequestInfo requestInfo)

   at DNTCommon.Web.Core.AntiDosMiddleware.Invoke(HttpContext context, IOptionsSnapshot`1 antiDosConfig, IAntiDosFirewall antiDosFirewall)

   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

AntiDosMiddleware does not work as expected

I use this AntiDosMiddleware in my app and it seems to not work fine yet.
this middleware ban request out of allowed requests count defined in appsettings.json

I added a db log and this is the result:

untitled

by calling same url Continuously, my IP banned, once in 6th request and once in 37th request but AllowedRequests is 500 !

When PersianDateModelBinder added globaly, it doesn't work

Summary of the issue

PersianDateModelBinder uses globally not work without BinderAttribute [ModelBinder(BinderType = typeof(PersianDateModelBinder))]
Also totally it doesn't bind value.

Environment

DNTCommon.Web.Core version: 2.9.2
.NET Core SDK version: 5
IDE: vs 16.8.2

Rss Items Not Showing

Summary of the issue

rss items not showing

Environment

DNTCommon.Web.Core version: 3.4.0
.NET Core SDK version: 6
IDE: Rider

Example code/Steps to reproduce:

var groups = _uow.Set<ProductGroup>()
                .OrderByDescending(x=>x.Id)
                .Skip(0)
                .Take(10)
                .ToList();

            var list = new List<FeedItem>();

            foreach (var group in groups)
            {
                list.Add(new FeedItem()
                {
                    Title = group.Name,
                    Content = group.Description,
                    Url = "http://www.helpdesk2.ir/"+group.Name,
                    AuthorName = "HelpDesk Writer",
                    PublishDate =group.CreationDate,
                    LastUpdatedTime = group.ModificationDate.HasValue?group.ModificationDate.Value:group.CreationDate
                });
            }
            
            var feedChannel = new FeedChannel()
            {
                CultureName = "fa-Ir",
                FeedTitle = "HelpDesk2 Shop",
                FeedDescription = "خرید انواع تجهیزات دیجیتال",
                FeedCopyright = "HelpDesk2.ir",
                RssItems = list
            };

            return new FeedResult(feedChannel);`

Output:

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" version="2.0">
  <channel>
  <description>‫خرید انواع تجهیزات دیجیتال</description>
  <copyright>HelpDesk2.ir</copyright>
  <title>HelpDesk2 Shop</title>
  <language>fa-IR</language><atom:link href="https://localhost:5001/feed/rss" rel="self" type="application/rss+xml" />
  <link>https://localhost:5001/</link></channel>
</rss>

Exception message:
Full Stack trace:


DisplayNameAttribute?

من برای ساختار چند زبانه DisplayNameAttribute رو override کردم و باتوجه به ساختار چندزبانه ازش استفاده میکنم

public class DisplayNameLocalizationAttribute : DisplayNameAttribute

اما زمانی که میخوام نام کنترلر ها رو بدست بیارم نام کنترلرها خالی می باشد
از این تابع استفاده میکنم
GetAllSecuredControllerActionsWithPolicy

Method not found: 'System.Threading.Tasks.Task DNTCommon.Web.Core.IWebMailService.SendEmailAsync'

Summary of the issue

can u help me? i tried everything about it.
method is ther i can find and useit. but in runtime i get this error

Environment

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return _webMailService.SendEmailAsync(
            _smtpConfig.Value,
            new[] { new MailAddress { ToName = "", ToAddress = email }, },
            subject,
            message
        );
    }
DNTCommon.Web.Core version:  latest
.NET Core SDK version: 
IDE: 

Example code/Steps to reproduce:

paste your core code

Output:

Exception message:
Full Stack trace:

DateTimeModelBinder Exception

Summary of the issue

Hi dear vahid.
When i updated to new version of DNTCommon.Web.Core, it occurs exception.

Environment

DNTCommon.Web.Core version: 2.9.1
.NET Core SDK version: 5 
IDE: VS 16.8.2

Example code/Steps to reproduce:

Your Test WebApp

Exception message:
Full Stack trace:
System.MissingMethodException: Method not found: 'System.Nullable`1<System.DateTime> DNTPersianUtils.Core.PersianDateTimeUtils.ToGregorianDateTime(System.String, Boolean)'.
   at DNTCommon.Web.Core.PersianDateModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BinderTypeModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value, Object container)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

1
2

DNTCommon.Web.Core.ProtectionProviderService

سلام
توی فایل لاگ این بخش مرتب خطا میده
The key Invalid protected payload. Fall through. was not found in the key ring.
[
{
"Key": "e52974eb-b2e5-4ad0-8b8f-d6092646beda",
"Value": "Invalid protected payload. Fall through."
},
{
"Key": "{OriginalFormat}",
"Value": "The key {e52974eb-b2e5-4ad0-8b8f-d6092646beda} was not found in the key ring."
}
]

ServerCertificateValidationCallback در smtpConfig

درود
آیا امکان دارد در تنظیمات یا همان
SmtpConfig
گزینه های
bool UseSSL
bool ServerCertificateValidationCallback
اضافه شود تا بجای فراخوانی تابع با پارامترها بصورت یکپارچه این تنظیمات اعمال شود؟

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.