HttpRequestBase in ASP.NET Core 6 MVC - asp.net-core-6.0

var redirectUrl = new UrlHelper(Request.RequestContext).Action(urlActionContext);
Request class this code is throwing the following error - I am creating an ASP.NET Core 6.0 MVC web app:
I tried importing System.Web but still of no use.

Request class this code is throwing the following error - I am
creating an ASP.NET Core 6.0 MVC
This pattern used to use in ASP.NET Core 2.2 or before. In Dotnet6 lot more efficient way available. For instance, LinkGenerator, IUrlHelper can do the same.
If you opt to get the redirectUrl from UrlActionContext you can follow below code snippet
If you are In Controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
namespace DotNet6MVCWebApp.Controllers
{
public class ActionHelperController : Controller
{
private readonly LinkGenerator _linkGenerator;
public ActionHelperController(LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public IActionResult Index()
{
UrlActionContext urlActionContext = new UrlActionContext();
urlActionContext.Controller = "Members";
urlActionContext.Action = "MemberList";
var redirectUrl = _linkGenerator.GetUriByAction(HttpContext, action: urlActionContext.Action, controller: urlActionContext.Controller, null, HttpContext.Request.Scheme);
return Redirect(redirectUrl);
}
}
}
If you are In Middleware:
public class ActionHelperMiddleware
{
private readonly RequestDelegate _next;
private readonly LinkGenerator _linkGenerator;
public ActionHelperMiddleware(RequestDelegate next, LinkGenerator linkGenerator)
{
_next = next;
_linkGenerator = linkGenerator;
}
public async Task InvokeAsync(HttpContext httpContext)
{
UrlActionContext urlActionContext = new UrlActionContext();
urlActionContext.Controller = "LoopUpload";
urlActionContext.Action = "Index";
var url = _linkGenerator.GetUriByAction(httpContext, action: urlActionContext.Action, controller: urlActionContext.Controller, null, httpContext.Request.Scheme);
await _next(httpContext);
}
}
Output:
Note: For more details you could refer to official document here.

Related

extended OrmLiteAuthRepository not binding properly

I extended the class OrmLiteAuthRepository
In the app host i inject it into the container. I test it using requiredrole controller and it never calls the methods for my custom security checks.
Even though i get redirect to http://localhost:5000/?redirect=%2fRequiresRole#f=Unauthorized
SO i just verified the the main simple contrustor is called when teh application starts. So it is using my clss. but not calling the get\haspermission methods.
[RequiredRole("TheRole")]
public class RequiresRoleController : ServiceStackController
{
public ActionResult Index()
{
var session = SessionAs<CustomUserSession>();
return View(session);
}
}
using System;
using System.Collections.Generic;
using cbw.service.interfaces.Services;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Data;
using ServiceStack.Host;
using ServiceStack.Messaging;
namespace cbw.mvc.web.service.Providers
{
public class MyOrmLiteAuthRepository : OrmLiteAuthRepository
{
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory) : base(dbFactory) { }
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory, string namedConnnection = null)
: base(dbFactory, namedConnnection)
{
DbFactory = dbFactory;
NamedConnnection = namedConnnection;
}
public IDbConnectionFactory DbFactory { get; set; }
public string NamedConnnection { get; set; }
public override ICollection<string> GetPermissions(string userAuthId)
{
var permissions = base.GetPermissions(userAuthId);
using (var ss = HostContext.ResolveService<SecurityService>(new BasicRequest()))
{
permissions = ss.UserPermissions(Convert.ToInt32(userAuthId));
}
return permissions;
}
public override bool HasPermission(string userAuthId, string permission)
{
var hasPermission = base.HasPermission(userAuthId, permission);
using (var ss = HostContext.ResolveService<SecurityService>(new BasicRequest()))
{
hasPermission = ss.UserHasPermInRoleOrGroup(permission, Convert.ToInt32(userAuthId));
}
return hasPermission;
}
}
}
Apphost.cs
using System;
using System.Net;
using cbw.mvc.web.service.Providers;
using cbw.service.interfaces.Services;
using cbw.service.interfaces.Validators;
using cbw.service.models.Models;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.OrmLite;
using ServiceStack.Caching;
using ServiceStack.Data;
using ServiceStack.Mvc;
using ServiceStack.Text;
using ServiceStack.Validation;
namespace cbw.mvc.web.service
{
public class AppHost : AppHostBase
{
public AppHost() : base("ServiceStack + .NET Core", typeof(StartupService).Assembly) { }
public override void Configure(Funq.Container container)
{
Plugins.Add(new RazorFormat());
//Works but recommend handling 404 at end of .NET Core pipeline
//this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
this.CustomErrorHttpHandlers[HttpStatusCode.Unauthorized] = new RazorHandler("/login");
//To include null values in the json globally
JsConfig.IncludeNullValues = true;
//This is mandate. We need "IncludeNullValuesInDictionaries = true" to include null values
JsConfig.IncludeNullValuesInDictionaries = true;
//To automatically wired up for you on all HTTP Verbs (GET, POST, etc)
//And built-in endpoints, i.e. JSON, XML, JSV, HTML, CSV, SOAP
Plugins.Add(new CorsFeature());
//To add registration feature
Plugins.Add(new RegistrationFeature());
//To add validation feature
Plugins.Add(new ValidationFeature());
container.RegisterValidators(
typeof(InsertCompanyValidator).Assembly,
typeof(UpdateCompanyValidator).Assembly,
typeof(DeleteCompanyValidator).Assembly
);
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[]
{
new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
new DigestAuthProvider(AppSettings), //Sign-in with HTTP Digest Auth
new TwitterAuthProvider(AppSettings), //Sign-in with Twitter
new FacebookAuthProvider(AppSettings), //Sign-in with Facebook
new GithubAuthProvider(AppSettings), //Sign-in with GitHub OAuth Provider
new GoogleAuthProvider(AppSettings), //Sign-in with Google OAuth Provider
new YandexAuthProvider(AppSettings), //Sign-in with Yandex OAuth Provider
new VkAuthProvider(AppSettings), //Sign-in with VK.com OAuth Provider
})
{
HtmlRedirect = "/",
//IncludeRegistrationService = true,
});
// i.e. Register in Memory Cache Client
//AutoQuery
Plugins.Add(new AutoQueryFeature { MaxLimit = 100000 });
container.Register<IAuthRepository>(c =>
new MyOrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
{
UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
});
;
bool ShouldWipeAndReloadDb = false;
var environmentVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (environmentVariable == "LocalMemory" || environmentVariable == "LocalSQLServer")
{
ShouldWipeAndReloadDb = true;
//Init auth tables
container.Resolve<IAuthRepository>().InitSchema();
}
var authRepo = (MyOrmLiteAuthRepository)container.Resolve<IAuthRepository>();
//Wipe and reload if using in memory SQL
if (ShouldWipeAndReloadDb)
{
DatabaseInitService dis = new DatabaseInitService();
dis.ResetDatabase();
SessionService.ResetUsers(authRepo);
dis.InitializeTablesAndData();
}
}
}
}
You’re using [RequiredRole] but you’re only overriding the HasPermission/GetPermissions APIs, you need to have overridden the HasRole/GetRoles APIs instead.

Calling Hub method from a controller's action in ASPNetCore MVC application using SignalR

I would like the ASPNetCore2.0 webapp I'm working on to send a notification to specific users using SignalR. I would like to call the hub's method from another controller's action (as opposed to a client's JS call).
I have learned that this is not how SignalR is intended to be used, but I've found many users who had the same 'desire' and also some solutions.
I have checked several proposed solutions, but the simplest and cleaner seemed to be the accepted answer to this post: Get Hub Context in SignalR Core from within another object.
So I gave it a go, and I get no errors at all. The server's output is error-free, and so are the browser's console and network tabs (I'm using Chrome). When debugging, the flow is smooth and the program does exactly what it should do... except the users don't get any notification...
Do any of you spot the problem?
I created a class that contains the shared methods for the hub:
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace WebApp.Hubs
{
public class HubMethods
{
private readonly IHubContext<PostsHub> _hubContext;
public HubMethods(IHubContext<PostsHub> hubContext)
{
_hubContext = hubContext;
}
public async Task Notify(string postId, string sender, List<string> users)
{
await _hubContext.Clients.Users(users).SendAsync("Notify", sender, postId);
}
}
}
Then I created a hub:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace WebApp.Hubs
{
[Authorize]
public class PostsHub : Hub
{
private HubMethods _hubMethods;
public PostsHub(HubMethods hubMethods)
{
_hubMethods = hubMethods;
}
public async Task Notify(string postId, string sender, List<string> users)
{
await _hubMethods.Notify(postId, sender, users);
}
}
}
Added these bits to Startup's ConfigureServices method:
[...]// Services before these...
services.AddSignalR();
services.AddScoped<HubMethods>();
services.AddMvc();
And Startup's Configure method:
app.UseSignalR(routes =>
{
routes.MapHub<PostsHub>("/postshub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Then these lines to the view:
<script src="~/lib/signalr/signalr.js"></script>
#await Html.PartialAsync("_NotifyScriptsPartial")
And this is "_NotifyScriptsPartial.cshtml":
<script>
var connection = new signalR.HubConnectionBuilder().withUrl('/PostsHub').build();
connection.on('Notify', function (sender, postId) {
var post = postId;
var sentBy = sender;
var content = '<a href=\'#\' class=\'close\' data-dismiss=\'alert\' aria-label=\'close\'>×</a>' +
'You just received a new comment from <strong>' +
sentBy + '</strong>. Click <a href = \'#\' class=\'alert-link\' >here</a> to view the post.'
var alert = document.createElement('div');
alert.classList.add('alert', 'alert-info', 'alert-dismissible');
alert.html(content);
document.getElementById('pageContent').appendChild(alert);
});
</script>
Finally, in the controller that is supposed to send the notification, I added these:
public class PostsController : Controller
{
private readonly HubMethods _hubMethods;
public PostsController(HubMethods hubMethods)
{
_hubMethods = hubMethods;
}
// POST: Create a new post
[Authorize]
[HttpPost]
public async Task<IActionResult> Create(DetailsModel model, List<string> readers)
{
if (ModelState.IsValid)
{
// Do stuff here... including creating the newPostId, userId and receipients variables used below
await _hubMethods.Notify(newPostId, userId, receipients);
// Do more stuff and eventually...
return View();
}
}
}
Any idea?
In Asp.Net Core 2.1 I can use hub like this, It solves my problem, also You used like this in your controller. Hope it helps.
public class SomeController : Controller
{
private readonly IHubContext<MyHub> _myHub;
public SomeController (IHubContext<MyHub> myHub)
{
_myHub = myHub;
}
public void SomeAction()
{
//for your example
_myHub.Clients.All.SendAsync("Notify", "data");
}
}
I can get the "data" text from browser's console. If you use jQuery in your project, add those codes between jQuery(document).ready(function () { }); because you tried to load a partial html and I think your code needs to run after ready() event. Sorry If I misunderstood you.

System.IO.InvalidDataException : ServiceStackHost.Instance has already been set (BasicAppHost)

I'm getting an error when i try to run some tests on my servicestack web service.
I'm using ServiceStack 4.5.8 and Nunit 3.5. The solution was created initially from a ServiceStackVS template.
The error, which appears on a number of tests, is
System.IO.InvalidDataException : ServiceStackHost.Instance has already been set (BasicAppHost)</br>
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.</br>
at ServiceStack.ServiceStackHost.Init()</br>
at MyApp.Tests.EchoServiceUnitTests.OneTimeSetup() in </br>
C:\Repos\MyApp\Myapp\MyApp.Tests\EchoServiceUnitTests.cs:line 45 </br>
--TearDown</br>
at MyApp.Tests.EchoServiceUnitTests.TestFixtureTearDown() in </br>C:\Repos\MyApp\MyApp\MyApp.Tests\EchoServiceUnitTests.cs:line 54
One of the tests that regularly generates this error is
namespace Tests
{
[TestFixture]
public class EchoServiceUnitTests
{
private ServiceStackHost appHost;
[OneTimeSetUp]
public void OneTimeSetup()
{
this.appHost = new BasicAppHost(typeof(EchoService).Assembly).Init();
}
[OneTimeTearDown]
public void TestFixtureTearDown()
{
this.appHost.Dispose();
}
[Test]
public void TestService()
{
const string Message = "Hello";
var service = this.appHost.Container.Resolve <EchoService>();
var response = (EchoResponse)service.Any(new Echo
{
Message = Message
});
Assert.That(response.Message,
Is.EqualTo(Message));
}
}
}
the service for this is
namespace ServiceInterface
{
public class EchoService : Service
{
public object Any(Echo request)
{
return new EchoResponse {Message = request.Message};
}
}
}
[Route("/Echo")]
[Route("/Echo/{Message}")]
public class Echo : IReturn<EchoResponse>
{
public string Message { get; set; }
}
public class EchoResponse : IHasResponseStatus
{
public EchoResponse()
{
this.ResponseStatus = new ResponseStatus();
}
public string Message { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
And finally my apphost
namespace MyApplication
{
using System;
using Funq;
using ServiceInterface;
using ServiceModel.Validators;
using ServiceStack;
using ServiceStack.Admin;
using ServiceStack.Api.Swagger;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Logging.NLogger;
using ServiceStack.MsgPack;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.SqlServer.Converters;
using ServiceStack.ProtoBuf;
using ServiceStack.Razor;
using ServiceStack.Validation;
using ServiceStack.VirtualPath;
using ServiceStack.Wire;
public class AppHost : AppHostBase
{
public static ILog Log = LogManager.GetLogger(typeof(AppHost));
public AppHost()
: base("MyApp",
typeof(HelloService).Assembly) { }
public override void Configure(Container container)
{
LogManager.LogFactory = new NLogFactory();
Log = LogManager.GetLogger(this.GetType());
this.Plugins.Add(new RazorFormat());
this.Plugins.Add(new PostmanFeature());
this.Plugins.Add(new SwaggerFeature());
this.Plugins.Add(new AdminFeature());
var ormSettings = new AppSettings();
container.Register <ICacheClient>(new MemoryCacheClient());
var dbFactory = new OrmLiteConnectionFactory(ormSettings.GetString("SqlDbConnection"),
SqlServerDialect.Provider);
dbFactory.RegisterConnection("Database2",
ormSettings.GetString("Sql2Connection"),
SqlServerDialect.Provider);
SqlServerDialect.Provider.RegisterConverter<DateTime?>(new SqlServerDateTimeConverter());
this.Plugins.Add(new RequestLogsFeature
{
RequestLogger = new CsvRequestLogger(files: new FileSystemVirtualPathProvider(this,
this.Config.WebHostPhysicalPath),
requestLogsPattern: "requestlogs/{year}-{month}/{year}-{month}-{day}.csv",
errorLogsPattern: "requestlogs/{year}-{month}/{year}-{month}-{day}-errors.csv",
appendEvery: TimeSpan.FromSeconds(1)),
EnableRequestBodyTracking = true,
EnableResponseTracking = true,
EnableErrorTracking = true,
});
this.Plugins.Add(new AutoQueryDataFeature
{
MaxLimit = 1000
});
this.Plugins.Add(new AutoQueryFeature());
var sse = new ServerEventsFeature
{
StreamPath = "/event-stream",
HeartbeatPath = "/event-heartbeat",
UnRegisterPath = "/event-unregister",
SubscribersPath = "/event-subscribers",
LimitToAuthenticatedUsers = false,
IdleTimeout = TimeSpan.FromSeconds(30),
HeartbeatInterval = TimeSpan.FromSeconds(10),
NotifyChannelOfSubscriptions = true,
};
this.Plugins.Add(sse);
Plugins.Add(new AdminFeature());
Plugins.Add(new WireFormat());
Plugins.Add(new MsgPackFormat());
Plugins.Add(new ProtoBufFormat());
}
}
}
I've tried a variety of suggestions including making the apphost in the test static, but nothing seems to work for me. I then tried the following test which also generated the same error which suggests to me that there is something in the apphost which is wrong but I can't see what.
[TestFixture(Category = "AppHost")]
public class AppHostTests
{
/// <summary>
/// The app host doesnt throw exception.
/// </summary>
[Test]
public void AppHostDoesntThrowException()
{
var apphost = new AppHost();
Assert.That(() => apphost.Init(),
Throws.Nothing);
}
}
The tests that generate this error whether I am using NCRUNCH (set to run one at a time) or if I use resharpers run all tests. It's generally the same tests that generate this error, though that seems to vary. In all cases, if I then run the tests manually they all pass.
You can only have 1 AppHost initialized and running at the same time where somehow NCrunch test is being run whilst there is another AppHost still in use. Maybe you can try debugging and setting a breakpoint that checks if ServiceStackHost.Instance is not null before trying to initialize another AppHost.
Note the AppHostBase is an ASP.NET Web App which may be causing the interference if it's running in the same project as the unit tests. If you want an integration test use AppSelfHostBase instead which you would use in place of BasicAppHost where you'd want to run a full integration test.

ASP.NET Web Api 2, Ninject, OWIN, and IIS

I'm using Ninject for dependency injection in my ASP.NET Web Api 2 project. Everything is working perfectly locally through Visual Studio and IIS Express, but when I deploy to IIS, the dependency's are not resolved. Below is my Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = new HttpConfiguration();
webApiConfiguration.EnableCors();
webApiConfiguration.SuppressDefaultHostAuthentication();
webApiConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
webApiConfiguration.MapHttpAttributeRoutes();
app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
ConfigureAuth(app);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
app.Run(async context =>
{
await context.Response.WriteAsync("Welcome to Web API");
});
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Load(new CourseModule(), new DataPullModule(), new DegreeModule(), new ResponseModule(), new RestSharpModule());
return kernel;
}
}
The error I get is when trying to access one of my controllers is below:
An error occurred when trying to create a controller of type 'DegreeController'. Make sure that the controller has a parameterless public constructor.
Here is my constructor for the DegreeController:
public DegreeController(IDegreeMapper degreeMapper, IDegreeRepository degreeRepository)
{
_degreeMapper = degreeMapper;
_degreeRepository = degreeRepository;
}
And here is the DegreeModule where I bind interfaces to classes.
public class DegreeModule : NinjectModule
{
public override void Load()
{
Bind<IDegreeController>().To<DegreeController>().InRequestScope();
Bind<IDegreeMapper>().To<DegreeMapper>().InRequestScope();
Bind<IDegreeRepository>().To<DegreeRepository>().InRequestScope();
Bind<IDegreeRatingCalculator>().To<DegreeRatingCalculator>().InRequestScope();
}
}
var kernel = CreateKernel();
app.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(configuration);

How to set log4net's log file location in autofac?

I am now adding controller log by following this post: Using Autofac to inject log4net into controller
After doing that, I can get my application run correctly. Below are the details:
LogInjectionModule here:
public class LogInjectionModule:Module
{
protected override void AttachToComponentRegistration(Autofac.Core.IComponentRegistry componentRegistry, Autofac.Core.IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
}
static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var t = e.Component.Activator.LimitType;
e.Parameters = e.Parameters.Union(new[]
{
new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))
});
}
}
DependencyRegister here:
private void RegisterDependency()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
builder.RegisterType<BookContext>().As<IDbContext>().SingleInstance().PreserveExistingDefaults();
builder.RegisterType<ManagerRepository>().As<IManager>().InstancePerHttpRequest();
builder.RegisterType<BookLendRepository>().As<IBookLend>().InstancePerHttpRequest();
builder.RegisterType<BookPlaceRepository>().As<IBookPlace>().InstancePerHttpRequest();
builder.RegisterType<BookRepository>().As<IBook>().InstancePerHttpRequest();
builder.RegisterType<BookTypeRepository>().As<IBookType>().InstancePerHttpRequest();
builder.RegisterType<StudentRepository>().As<IStudent>().InstancePerHttpRequest();
builder.RegisterType<ManagerService>().As<IManagerService>().InstancePerHttpRequest();
builder.RegisterModule(new LogInjectionModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
MyController here:
public HomeController(
IManagerService managerService
,ILog logger
)
{
this.managerService = managerService;
this.logger = logger;
}
private readonly IManagerService managerService;
private readonly ILog logger;
public ActionResult Index(Manager manager)
{
logger.Info("test");
return View();
}
And when I debug to logger.Info("test") , I can get the log instance. But the problem is , where is the log file's location? is there any config for the integrated log4net that I can decide where to put the log file?
The question isn't related to Autofac. Log4net is a standalone library. You can read more about log4net on its homepage and how to configure it here.

Resources