AspNetBoilerplate - HttpContext is null in custom TenantResolveContributor - aspnetboilerplate

Documentation
I've read the documentation at https://aspnetboilerplate.com/Pages/Documents/Multi-Tenancy
I added a custom TenantResolveContributor to the application project and added it to the collection in WebModule.PreInitialize.
Configuration.MultiTenancy.Resolvers.Add<NameTenantResolveContributor>();
In WebModule.Initialize, I resolve my TenantAppService so it can be injected into RouteConfig.
TenantAppService tenantAppService = IocManager.Resolve<TenantAppService>();
RouteConfig.RegisterRoutes(RouteTable.Routes, tenantAppService);
When execution reaches RouteConfig, it correctly goes into NameTenantResolveContributor, but the HttpContext is null.
I'm not sure what I need to do to fix this.
Abp package version : 6.0.0
Base framework: .Net
Request is not available in this context
at System.Web.HttpContext.get_Request()
at DemoApp.MultiTenancy.NameTenantResolveContributor.ResolveTenantId() in >D:\src\ABP\DemoProject\6.0.0\src\DemoProject.Application\MultiTenancy\NameTenantResolveContributor.cs:line 40
at Abp.MultiTenancy.TenantResolver.GetTenantIdFromContributors()
The stack trace is oddly brief and undescriptive. When I copy the details, the message is
System.Web.HttpException
HResult=0x80004005
Message=Request is not available in this context
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.MultiTenancy;
using Abp.Text;
using Abp.Web.MultiTenancy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace DemoApp.MultiTenancy
{
public class NameTenantResolveContributor : ITenantResolveContributor, ITransientDependency
{
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ITenantStore _tenantStore;
public NameTenantResolveContributor(IMultiTenancyConfig multiTenancyConfig, ITenantStore tenantStore)
{
_multiTenancyConfig = multiTenancyConfig;
_tenantStore = tenantStore;
}
public int? ResolveTenantId()
{
string tenancyName = "";
string[] urlParts = null;
var httpContext = HttpContext.Current;
if (httpContext == null)
{
return null;
}
//This is where the error occurs
urlParts = httpContext.Request.Url.Segments.Select(x => x.TrimEnd('/')).Skip(1).ToArray();
tenancyName = urlParts[0].ToLower();
var tenantInfo = _tenantStore.Find(tenancyName);
if (tenantInfo == null)
{
return null;
}
return tenantInfo.Id;
}
}
}

Related

Download Manager in Xamarin results in "Unsuccessful Download" notification on smartphone, with no exception thrown

I can download some files in a random page (a pdf from google, for example) but in the page I need to download them from, I get "Unsuccessful Download" notification on smartphone, with no exception thrown for me. Is there a way to know why this is happening?
Code from the renderer that I use to download below.
using Android.App;
using Android.Webkit;
using MPS.Libertas.Mobile.Droid.Renderers;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Android.Content;
using Xamarin.Essentials;
using System.IO;
using System;
using Android.Widget;
using static Android.Provider.MediaStore;
[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(MPS_MyWebViewRenderer))]
namespace MPS.Libertas.Mobile.Droid.Renderers
{
internal class MPS_MyWebViewRenderer : WebViewRenderer
{
public MPS_MyWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Download += OnDownloadStart;
}
private void OnDownloadStart(object sender, Android.Webkit.DownloadEventArgs e)
{
try
{
var url = e.Url;
string url_formatted = url.Replace("blob:", "");
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url_formatted));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetMimeType("application/pdf");
                // if this path is not create, we can create it.
                string thmblibrary = FileSystem.AppDataDirectory + "/download";
if (!Directory.Exists(thmblibrary))
Directory.CreateDirectory(thmblibrary);
request.SetDestinationInExternalFilesDir(Android.App.Application.Context, FileSystem.AppDataDirectory, "download");
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
dm.Enqueue(request);
}
catch (System.Exception ex)
{
var message = ex.Message;
throw;
}
}
}
}

GraphQLAuthorize attribute not firing [graphql]

I am working on the qraphQL api and I am trying to use authorization attribute GraphQLAuthorize in GraphQL.Server.Authorization.AspNetCore; I have created policy in startup.cd configureService but not recognized by GraphQLAuthorize attribute.
The [GraphQLAuthorize(Policy = "AUTHORIZED")] is not working.
while the AuthorizeWith("AUTHORIZED") is working
using GraphQL.Repository.GraphQL.Types;
using GraphQL.Repository.Repositories;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using GraphQL.Server.Authorization.AspNetCore;
namespace GraphQL.Repository.GraphQL
{
[GraphQLAuthorize(Policy = "AUTHORIZED")]
public class MenuQuery : ObjectGraphType
{
public MenuQuery(MenuRepository menuRepository)
{
Field<ListGraphType<NavigationMenuType>>(
"NavigationMenu",
arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "applicationId" }),
resolve: context =>
{
var user = (ClaimsPrincipal)context.UserContext;
var applicationId = context.GetArgument<int>("applicationId");
return menuRepository.GetNavigationMenus(applicationId);
});
}
}
}
//startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//using GraphQL;
using GraphQL.Server;
using Microsoft.EntityFrameworkCore;
using GraphQL.Repository.Entities;
using GraphQL.Repository.Repositories;
using GraphQL.Repository.GraphQL;
using GraphQL.Repository.GraphQL.Types;
using Microsoft.Extensions.DependencyInjection.Extensions;
using GraphQL.Server.Ui.GraphiQL;
using GraphQL.Server.Ui.Playground;
namespace GraphQL.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MenuManagementDevContext>(options =>
options.UseSqlServer(Configuration["ConnectionStrings:CarvedRockContext"]));
services.AddScoped<MenuRepository>();
services.AddScoped<MenuQuery>();
services.AddScoped<NavigationMenuType>();
services.AddScoped<RoleNavigationMenuType>();
services.AddScoped<RoleType>();
services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
services.AddScoped<MenuSchema>();
services.AddGraphQL(o => { o.ExposeExceptions = true; })
.AddGraphQLAuthorization(options =>
{
options.AddPolicy("AUTHORIZED", p => p.RequireAuthenticatedUser());
})
.AddGraphTypes(ServiceLifetime.Scoped).AddUserContextBuilder(httpContext => httpContext.User)
.AddDataLoader()
.AddWebSockets();
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder =>
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseWebSockets();
app.UseGraphQLWebSockets<MenuSchema>("/graphql");
app.UseGraphQL<MenuSchema>();
app.UseGraphiQLServer(new GraphiQLOptions());
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
}
}
}
Any help would be appreciated!

Converting Request.RequestUri to ASP.NET Core 2.1

What is the ASP.NET Core MVC equivalent to Request.RequestURI?
I am trying to set up an ASP.NET Core implementation of JSGrid. The example provided they provide is pre-Core so I am having some problems converting the source code to ASP.NET Core.
Getting stuck on converting one last error on Request.RequestUri.Query
I read this post but couldn't figure out how it applied to my case and it's also 3 years old. I'm hoping that Microsoft has provided a new using which will handle RequestUri by now but I can't seem to find it.
Here's my controller so far.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Deviation.Data;
using System.Collections.Specialized;
using System.Web;
namespace Deviation.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class JSGridController : ControllerBase
{
private readonly DeviationContext _context;
public JSGridController(DeviationContext context)
{
_context = context;
}
public IEnumerable<object> Get()
{
ClientFilter filter = GetFilter();
var result = _context.MissedDeliveries.Where(c =>
(String.IsNullOrEmpty(filter.Delivery) || c.Delivery.Contains(filter.Delivery))
);
return result.ToArray();
}
private ClientFilter GetFilter()
{
NameValueCollection filter = HttpUtility.ParseQueryString(Request.RequestUri.Query);
return new ClientFilter
{
Delivery = filter["Delivery"],
};
}
}
}
Many thanks to anyone who could provide a bit of guidance.
Try HttpContext.Request.Query :
var q = HttpContext.Request.Query;
var deliveries = q["Delivery"];
var delivery = q["Myquery"].FirstOrDefault();

how to override SignalR methods in mvc 5

I am working on a asp.net mvc5 project and I want to implement chatroom with signalR So I got Microsoft.Aspnet.SignalR from nuget and I used a SignalR Hub class for hub and now i want to override OnDisconnected() method .but I get error
'ChatHub.OnDisconnected()': no suitable method found to override
I dont know how to solve this problem please help me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace WebApplication3.Hubs
{
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
static ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
public void SendToSpecific(string name, string message, string to)
{
// Call the broadcastMessage method to update clients.
Clients.Caller.broadcastMessage(name, message);
Clients.Client(dic[to]).broadcastMessage(name, message);
}
public void Notify(string name, string id)
{
if (dic.ContainsKey(name))
{
Clients.Caller.differentName();
}
else
{
dic.TryAdd(name, id);
foreach (KeyValuePair<String, String> entry in dic)
{
Clients.Caller.online(entry.Key);
}
Clients.Others.enters(name);
}
}
public override Task OnDisconnected()
{
var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
string s;
dic.TryRemove(name.Key, out s);
return Clients.All.disconnected(name.Key);
}
}
}
For SignalR 2.1.0+, you need to use OnDisconected(bool stopCalled).
// Microsoft.AspNet.SignalR.Hub
// Summary:
// Called when a connection disconnects from this hub gracefully or due to a timeout.
//
// Parameters:
// stopCalled:
// true, if stop was called on the client closing the connection gracefully; false,
// if the connection has been lost for longer than the Microsoft.AspNet.SignalR.Configuration.IConfigurationManager.DisconnectTimeout.
// Timeouts can be caused by clients reconnecting to another SignalR server in scaleout.
//
// Returns:
// A System.Threading.Tasks.Task
public virtual Task OnDisconnected(bool stopCalled);

Property not found in web api

The Result property in actionExecutedContext.Result cannot be resolved. Any ideas why?
Here's my code.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http.Filters;
using System.Net.Http;
public class ValidateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var modelState = actionExecutedContext.ActionContext.ModelState;
if (!modelState.IsValid)
{
var errors = modelState
.Where(s => s.Value.Errors.Count > 0)
.Select(s => new KeyValuePair<string, string>(s.Key, s.Value.Errors.First().ErrorMessage))
.ToArray();
actionExecutedContext.Result = new HttpResponseMessage<KeyValuePair<string, string>[]>(errors, HttpStatusCode.BadRequest);
}
base.OnActionExecuted(actionExecutedContext);
}
}
Since the beta days of Web API, HttpActionExecutedContext hasn't had a Result property but a Response property instead.
You can assign the HttpResponseMessage instance to it.
See the framework source code here.

Resources