I'm setting a Session in my Asp.NET Code like this:
public class MyController : Controller
{
public ActionResult Index()
{
Session["AdminID"] = id;
return View();
}
}
But now I want to access this Session in a file which is not a Controller in the background of the project.
Is this possible?
S.th. like this:
public class MyClass
{
public int Foo()
{
return Session["AdminID"]
}
}
Use HttpContext.Current.Session:
using System.Web;
// ...
public int Foo()
{
return (int)HttpContext.Current.Session["AdminID"];
}
Related
I'm a newbine in ASP.NET Core, I see in the User property (in ClaimsPrincipal class) in my controller, it has User.IsInRole method, so how can I override it to call my service dependency and register in my application (I don't want to use extension method).
You can use ClaimsTransformation:
public class Startup
{
public void ConfigureServices(ServiceCollection services)
{
// ...
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
}
}
public class CustomClaimsPrincipal : ClaimsPrincipal
{
public CustomClaimsPrincipal(IPrincipal principal): base(principal)
{}
public override bool IsInRole(string role)
{
// ...
return base.IsInRole(role);
}
}
public class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var customPrincipal = new CustomClaimsPrincipal(principal) as ClaimsPrincipal;
return Task.FromResult(customPrincipal);
}
}
Controller method:
[Authorize(Roles = "Administrator")]
public IActionResult Get()
{
// ...
}
Role checking by Authorize attribute will use your overrided IsInRole method
For User.IsInRole, it is ClaimsPrincipal which is not registered as service, so, you could not replace ClaimsPrincipal, and you could not override IsInRole.
For a workaround, if you would not use extension method, you could try to implement your own ClaimsPrincipal and Controller.
CustomClaimsPrincipal which is inherited from ClaimsPrincipal
public class CustomClaimsPrincipal: ClaimsPrincipal
{
public CustomClaimsPrincipal(IPrincipal principal):base(principal)
{
}
public override bool IsInRole(string role)
{
return base.IsInRole(role);
}
}
ControllerBase to change ClaimsPrincipal User to CustomClaimsPrincipal User
public class ControllerBase: Controller
{
public new CustomClaimsPrincipal User => new CustomClaimsPrincipal(base.User);
}
Change the Controller from inheriting ControllerBase.
public class HomeController : ControllerBase
{
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
var result = User.IsInRole("Admin");
return View();
}
Change the logic in public override bool IsInRole(string role) based on your requirement
I writted this code (CustomHandle) for application log. But, i don't want to run this code on some actions.
CustomHandle.cs:
public class CustomHandle: ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
string FormVeri = "";
string QueryVeri = "";
foreach (var fName in filterContext.HttpContext.Request.Form)
{
FormVeri += fName + "= " + filterContext.HttpContext.Request.Form[fName.ToString()].ToString() + "& ";
}
foreach (var fQuery in filterContext.HttpContext.Request.QueryString)
{
QueryVeri += fQuery + "= " + filterContext.HttpContext.Request.QueryString[fQuery.ToString()] + "& ";
}
base.OnResultExecuted(filterContext);
}
}
FilterConfig.cs:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomHandle());
}
}
HomeController.cs:
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View();
}
CustomHandle works on Index and Login. But, CustomHandle is i don't want run on Login ActionResult.
Thanks,
Best Regards.
In MVC 5... instead of adding the action filter in FilterConfig.cs
add it to each Controller (or a base controller) - all actions will be affected.
use [OverrideActionFilter] to remove that filter for a specific action.
Example
[CustomHandle]
public class AnyController : Controller
{
public ActionResult Index() // has [CustomHandle] attribute
{
}
[OverrideActionFilter]
public ActionResult Login() // ignores the [CustomHandle] attribute
{
}
}
When a filter is injected into a controller class, all its actions are also injected. If you would like to apply the filter only for a set of actions, you would have to inject [CustomActionFilter] to each one of them:
[CustomHandle]
public ActionResult Index()
{
...
}
public ActionResult Login()
{
...
}
Public class is not working in wcf services. I have created one another public class and use into my service.svc but class is not accessible. Please see the following code.
ITest.cs
namespace TestProject.Services
{
[ServiceContract]
public interface ITest
{
[ServiceContract]
public interface ITest
{
[OperationContract]
DataTable SelectData(string sSectionName);
}
}
}
ITest.svc.cs
namespace TestProject.Services
{
public class Test: ITest
{
public DataTable SelectData(string sSectionName)
{
//do some work
}
}
}
Ohter New class
Public class connection
{
public int sum(int i, int b)
{
return i+b;
}
}
My connection class is not accessible in ITest.svc.cs. Please help
Try rewriting connection as such:
namespace TestProject.Services
{
Public class connection
{
public int sum(int i, int b)
{
return i+b;
}
}
}
When using ASP.NET Web Api 2 I always need to include the same code:
public IHttpActionResult SomeMethod1(Model1 model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//...
}
public IHttpActionResult SomeMethod2(Model2 model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//...
}
I would like to move validation to the base controller that will be executed on each request. But there are many methods to override and I don't know, which one should I use and how.
public class BaseController : ApiController
{
public void override SomeMethod(...)
{
if (!ModelState.IsValid)
{
// ???
}
}
}
Is there any example for validation in a base class for ASP.NET Web Api?
Example from asp.net
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
and add this attribute to your methods
[ValidateModel]
public HttpResponseMessage SomeMethod1(Model1 model)
I have a base controller:
Public MustInherit Class InjuredWorkerController(Of TManager As IInjuredWorkerManagerBase)
Then I have a home controller:
Public Class HomeController
Inherits InjuredWorkerController(Of IInjuredWorkerManager)
IInjuredWorkerManager inherits IInjuredWorkerManagerBase
Why does this throw a cast exception:
Dim manager = CType(filterContext.Controller, InjuredWorkerController(Of IInjuredWorkerManagerBase)).Manager
Unable to cast object of type 'MyClaim.Controllers.HomeController' to type 'MyClaim.Controllers.InjuredWorkerController`1[SAIF.Web.Mvc.MyClaim.IInjuredWorkerManagerBase]'.
You need to extract an interface for your InjuredWorkerController to make it work, since co- and contravariance only works with interfaces and delegates.
This code compiles and runs (C# console app, I'm not fluent in VB.Net...):
using System;
namespace TestApplication
{
public interface IInjuredWorkerController<out TManager>
where TManager : IInjuredWorkerManagerBase
{
TManager Manager { get; }
}
public abstract class InjuredWorkerController<TManager>
: IInjuredWorkerController<TManager>
where TManager : IInjuredWorkerManagerBase, new()
{
protected InjuredWorkerController()
{
Manager = new TManager();
}
public TManager Manager { get; private set; }
}
public interface IInjuredWorkerManagerBase
{
string Name { get; }
}
public interface IInjuredWorkerManager
: IInjuredWorkerManagerBase {}
public class InjuredWorkerManager : IInjuredWorkerManager
{
public string Name
{
get { return "Homer"; }
}
}
public class HomeController
: InjuredWorkerController<InjuredWorkerManager> {}
internal class Program
{
private static void Main()
{
var controller = new HomeController();
var manager = ((IInjuredWorkerController<IInjuredWorkerManagerBase>)controller).Manager;
Console.Out.WriteLine(manager.Name);
Console.ReadKey();
}
}
}
Eric Lippert's blog series on the subject is a must read.