Property not found in web api - asp.net-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.

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

Why MapFallbackToController is not working: HTTP 401 UNAUTHORIZED Asp.net Core

I finished my app and i want to publish it into web.
Working on core 3.1.1 + angular2.
I created Fallback controller for routes.
It seems MapFallbackToController is not working. I don't have acceses to these files because i'm unauthorized, but why?
When i do "dotnet run" my page is blank and in the console:
Everything worked perfect until i moved angular files(wwwroot) into API proj.
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using RecipesApp.API.Controllers.Models.Data;
using RecipesApp.API.Data;
using RecipesApp.API.Helpers;
namespace RecipesApp.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<DataContext>( x=> x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers().AddNewtonsoftJson(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
services.AddAutoMapper(typeof(RecipesRepository).Assembly);
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IRecipesRepository, RecipesRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration
.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<LogUserActivity>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
// app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToController("Index", "Fallback");
});
}
}
}
My fallback class
public class Fallback : Controller
{
public IActionResult Index()
{
return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html"), "text/HTML");
}
}
}
Somewhere in your startup file, i think you have specified that before a request gets to a controller, an authorization is needed, hence the error. In your case, can you try putting the AllowAnonymous attribute in your Fallback file as this tells netcore to map back to the fallback controller in search for angular index.html file. So, something like this;
[AllowAnonymous]
public class Fallback : ControllerBase
{
public IActionResult Index()
{
return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html"), "text/HTML");
}
}
In your startup.cs file, inside your Configure() method, out the app.UseStaticFiles() after app.UseRouting(). That's all.

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

Resources