Converting Request.RequestUri to ASP.NET Core 2.1 - asp.net-web-api

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();

Related

AspNetBoilerplate - HttpContext is null in custom TenantResolveContributor

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;
}
}
}

OData endpoint: Is it possible to edit document service

Dears,
I've designed a OData endpoint, following this https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint
I'm done with it but I have a constraint: for all API features, the header must contain an Authorization key. This is done everywhere BUT in the service document. The service document is what you got when looking at URL https://SITE/api/v1:
{"#odata.context":"http://SITE/api/v1/$metadata","value":[{"name":"things","kind":"EntitySet","url":"things"},{"name":"others","kind":"EntitySet","url":"others"}]}
Hence, do you know how is generated such document service? Is it possible to edit it? Or even, is there way to check header in such a document service?
Thanks in advance for your help,
Kind regards,
Solved by myself using following module:
using System;
using System.Linq;
using System.Web;
namespace Api.Modules
{
public class AuthorizationModule : IHttpModule
{
public void Dispose(){}
private void Context_Authorization(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
if (!IsAuthorized(application.Context))
{
application.Context.Response.Status = "403 Forbidden";
application.Context.Response.StatusCode = 403;
application.CompleteRequest();
}
}
public bool IsAuthorized(HttpContext context)
{
if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
return false;
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
if (!authHeader.Equals(Properties.Resources.Authorization_Key))
{
return false;
}
return true;
}
public void Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(Context_Authorization);
}
}
}
If it helps...
Kind regards,

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.

SignalR in SharePoint

My project has a need for realtime user interaction and I think SignalR will solve my need. I'm technically on a SharePoint 2007 project, although I'm exclusively in application pages and thus barely use SharePoint at all. Regardless, I'm stuck in a 2.0 framework app pool in IIS.
My first approach was to try to create a 4.0 application as a sub-site. Unfortunately, that failed miserably. That approach works in a non-SharePoint world, but it appears that SharePoint has hijacked too much of the request pipeline for this approach to work for me.
So now I'm going down the path of creating a separate IIS Site that's 4.0 and using IIS rewrite rules to fake my app into thinking a particular subdirectory (/realtime/) is local and not a separate site so that I don't have to deal with cross domain request issues. The problem is I can't get IIS rewrite rules to rewrite to another http host (e.g. http://www.mySharepoint.com/_layouts/MySite/realtime/Hello.aspx to http://realtime.mySharePoint.com/Hello.aspx).
Any help with approach #1 or approach #2 or any alternative ideas would be greatly appreciated.
Here is what I did... Web App with signalR .net4.0, then your SharePoint Web App .net 2.
Add this to the global.asax in your Signalr project
RouteTable.Routes.MapHttpHandlerRoute("spproxy","spproxy/{*operation}", new SharePointRProxyHandler());
If you want to raise an event from SharePoint you can do a http POST to this new route URL for example
http://localhost:38262/spproxy
It will pass any posted data onto the httphandler below, that will then broadcast it to your clients.
Here is the code for MapHttpHandlerRoute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace System.Web.Routing
{
public class HttpHandlerRoute : IRouteHandler
{
private String _virtualPath = null;
private IHttpHandler _handler = null;
public HttpHandlerRoute(String virtualPath)
{
_virtualPath = virtualPath;
}
public HttpHandlerRoute(IHttpHandler handler)
{
_handler = handler;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
IHttpHandler result;
if (_handler == null)
{
result = (IHttpHandler)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
}
else
{
result = _handler;
}
return result;
}
}
public static class RoutingExtensions
{
public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
{
var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(physicalFile));
RouteTable.Routes.Add(routeName, route);
}
public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, IHttpHandler handler, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
{
var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(handler));
RouteTable.Routes.Add(routeName, route);
}
}
}
Or you could just post directly to a httphandler and get the handler to do a connection.Broadcast
namespace SharePointRProxy
{
/// <summary>
/// Summary description for SharePointRProxyHandler
/// </summary>
public class SharePointRProxyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
IConnectionManager connectonManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
IConnection connection = connectonManager.GetConnection<MyConnection>();
object payload = null; //Add payload here 'context.Request.Params["data"] ?'
JavaScriptSerializer jss = new JavaScriptSerializer();
var payloadJSON = jss.Serialize(payload);
connection.Broadcast(payloadJSON);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You could also use either an event handler calling a .net 4.0 web service or an http handler to grab requests from SharePoint and pass them over to a .net 4.0 application running your signalr code.
You can see an example of using an http handler here: http://spmatt.wordpress.com/2012/04/12/harnessing-signalr-in-sharepoint/

Resources