Usage of HttpContext in dotnet core 2.2 - httpcontext

I would like get key from sessions, but the compiler is complaining that the class is static when it is not. Can anyone please help me out?
using Microsoft.AspNetCore.Mvc;
using LitOnline_V1.Models;
using Microsoft.AspNetCore.Http;
namespace Test{
public class GetValidateUer{
public int GetUserValidation(){
var isValidated = HttpContext.Session.GetInt32("isValidated");
return isValidated;
}
}
}
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'

hope it help
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Some Code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Some Code
}

Related

Why does 'InputField' not contain a definition for 'text'?

I'm currently working on a Unity project for a college assignment, and I'm currently trying to connect a login/registration through PlayFab into a teammate's main menu for the game.
I've connected the PlayFabManager.cs script to the Input Fields for the email and password in the Unity editor, and something about my InputFields.cs file is preventing me from making any more progress.
I had to change the passwordInput and emailInput variables to TMP_InputField variables to achieve this, but now I am getting a compilation error in my project that says the following:
Assets\Scripts\InputField.cs(13,24): error CS1061: 'InputField' does not contain a definition for 'text' and no accessible extension method 'text' accepting a first argument of type 'InputField' could be found (are you missing a using directive or an assembly reference?)
Most places I look have people not including the "using UnityEngine.UI;" header at the top of the file, but that's included in my InputField.cs file.
Here's the code for my InputField.cs file:
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class InputField : MonoBehaviour
{
public InputField mainInputField;
public void Start()
{
mainInputField.text = "Enter text here...";
}
}
Here's the code for my PlayFabManager.cs file:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using Newtonsoft.Json;
using UnityEngine.UI;
using TMPro; // Needed for login input fields
public class PlayFabManager : MonoBehaviour
{
[Header("UI)")]
public Text messageText;
public TMP_InputField emailInput;
public TMP_InputField passwordInput;
// Register/Login/ResetPassword
public void RegisterButton() {
var request = new RegisterPlayFabUserRequest {
Email = emailInput.text,
Password = passwordInput.text,
RequireBothUsernameAndEmail = false
};
PlayFabClientAPI.RegisterPlayFabUser(request, OnRegisterSuccess, OnError);
}
void OnRegisterSuccess(RegisterPlayFabUserResult result) {
messageText.text = "Registered and Logged in";
}
public void LoginButton() {
}
// Start is called before the first frame update
void Start() {
Login();
}
// Update is called once per frame
void Login() {
var request = new LoginWithCustomIDRequest {
CustomId = SystemInfo.deviceUniqueIdentifier,
CreateAccount = true
};
PlayFabClientAPI.LoginWithCustomID(request, OnSuccess, OnError);
}
void OnSuccess(LoginResult result) {
Debug.Log("Successful login/account create.");
}
void OnError(PlayFabError error) {
Debug.Log("Error while loggin in/creating account.");
Debug.Log(error.GenerateErrorReport());
}
}
I would just remove the InputField.cs class as it fixes my errors, but it changes the functionality of the following code that my teammate has contributed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MenuControl : MonoBehaviour
{
public string newGameLevel;
public void NewUser() {
SceneManager.LoadScene(newGameLevel);
}
public void ExitButton() {
Application.Quit();
}
}
Any help would be much appreciated!
Wanted to provide the solution in case this happens to anyone in the future:
I solved the problem by changing the
public InputField mainInputField;
into an input variable that could receive the TMP_Imput like so: public TMPro.TMP_InputField mainInputField;

structuremap configuration asp.net mvc 4

I have a problem with MVC4 StructureMap configuration, when I run the project the compiler fires this error
No Default Instance defined for PluginFamily Mace_CrmSystem.Controllers.HomeController
this is my code
global.aspx code
namespace Mace_CrmSystem
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteTable.Routes.MapRoute("Oqla", "Oqla", new { controller = "Home", action = "index" });
RouteConfig.RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MyCustomeFactory());
ObjectFactory.Initialize(x => x.For<string>().Use<string>());
}
}
}
MycustomeFactory class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMap;
namespace Mace_CrmSystem
{
public class MyCustomeFactory : System.Web.Mvc.DefaultControllerFactory
{
protected override System.Web.Mvc.IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return StructureMap.ObjectFactory.GetInstance(controllerType) as System.Web.Mvc.IController;
}
}
}
Controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mace_CrmSystem.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public HomeController(string parameter)
{
TempData["Hi"] = "Hi";
}
public ActionResult Index()
{
return View();
}
}
public class logger
{
public void log()
{
}
}
}
what I noticed that when I add a parameter of type object like
public HomeController(logger parameter)
instead of
public HomeController(string parameter)
and
ObjectFactory.Initialize(x => x.For<logger>().Use<logger>());
instead of
ObjectFactory.Initialize(x => x.For<string>().Use<string>());
it works probably but with the string parameter it does not work .
so please couold anyone explain that for me.
From my understanding of StructureMap (and someone please correct me if I'm wrong) the reason you're seeing the behaviour that you're seeing is because StructureMap will use the longest constructor by default and attempt to fill in the parameters with the default instance registered with StructureMap.
In your instance you're not providing a default instance of string so StructureMap doesn't know how to resolve it.
If you wish to do what you're trying to do then your best bet is to look at creating a custom convention (see this answer for more information), however these do rely on knowing the name of the property your constructor is expecting.
Generally though, when dealing with strings your best bet is to move the string to an intermediate type and inject that instead.

Attribute methods derived from System.Web.Http.AuthorizeAttribute class are not called in Web Api 2

I want to derive an attribute from System.Web.Http.AuthorizeAttribute as follows:
using System.Web.Http.Controllers;
using WebApi = System.Web.Http;
namespace Memzuc.Net.Authorization {
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : WebApi.AuthorizeAttribute {
private static Logger logger = LogManager.GetCurrentClassLogger();
public AuthorizeAttribute() : base() {
logger.Debug("Memzuc.Net.Authorization.AuthorizeAttribute ctor");
}
protected override bool IsAuthorized(HttpActionContext actionContext) {
logger.Debug("Memzuc.Net.Authorization.AuthorizeAttribute.IsAuthorized called");
return base.IsAuthorized(actionContext);
}
public override void OnAuthorization(HttpActionContext actionContext) {
logger.Debug("Memzuc.Net.Authorization.AuthorizeAttribute.OnAuthorization called");
base.OnAuthorization(actionContext);
}
}
}
Sure I shall do some other useful things! And I use this attribute like so:
using System.Web.Http;
using MemAuth = Memzuc.Net.Authorization;
namespace Memzuc.Net.Controllers {
[RoutePrefix("main-risk")]
public class MainRiskController : ApiController {
[Route("")]
[MemAuth.Authorize]
public IEnumerable<MainRisk> Get() {
var repo = GetMainRiskRepo();
return repo.GetMainRiskList();
}
I see ctor records in the log when the application begins. But both IsAuhorized() and OnAuthorization() are not get called and MainRiskController.Get() method is entered without any authorization control.
Am I doing something wrong? Or is it necessary to register the new authorization attribute to somewhere?
I found the problem. The attribute and the controller that use it resides in different assemblies, which are referencing different versions of System.Web.Http. As the same version referenced the attribute worked.

How configure LightInject in ASP.NET MVC?

I use SimpleInjector in mvc with this code
public static class SimpleInjectorInitializer
{
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container container)
{
container.Register<IPersonRepository, PersonEntityRepository>();
}
}
but now I want to test LightInject Ioc in my mvc application but How ?
I wrote this code
[assembly: WebActivator.PostApplicationStartMethod(typeof(LightInjectInitializer), "InitializeLI")]
public static class LightInjectInitializer
{
public static void InitializeLI()
{
var container = new ServiceContainer();
InitializeContainer(container);
container.RegisterControllers(Assembly.GetExecutingAssembly());
container.EnableMvc();
}
private static void InitializeContainer(ServiceContainer container)
{
container.Register(typeof(PersonEntityRepository), typeof(IPersonRepository), new PerScopeLifetime());
}
}
but show me this error
No parameterless constructor defined for this object.
Can anyone help me for writing equivalent code that working in MVC ?
Sample Code : Download
I am the author of LightInject and would like to help you out.
This static initialize method? Where is it called from.
The reason that you get this error is probably because the initialize code did not execute.
If you would like further assistance, it would be valuable to see what you have in global.asax.cs.
This page also contains information about how to set this up.
http://www.lightinject.net/#mvc
Please change the controller registration line to:
container.RegisterControllers(typeof(MVCApplicationNamespace.Controllers.HomeController).Assembly);

How to add web API to an existing MVC Hottowel project

I have one Hottowel project created using it's template from Visual Studio. I want to add the Web API feature in that project. I have created a Web Api controller to the controller folder and tries to access like "http://localhost:53397/api/Values" But I get an error saying The resource cannot be found error.
My controller code looks like below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MvcApplication8.Controllers
{
public class ValuesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
I have the cs file in APP_start folder called BreezeWebApiConfig.cs which contains the logic to map the route like below.
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "api/{controller}/{action}"
);
Let me know If I am missing any configuration setting for Web APi.
Try to decorate your ApiController like bellow :
[BreezeController]
public class NorthwindIBModelController : System.Web.Http.ApiController {
readonly EFContextProvider<NorthwindIBContext> ContextProvider =
new EFContextProvider<NorthwindIBContext>();
[HttpGet]
public String Metadata() {
return ContextProvider.Metadata();
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return ContextProvider.SaveChanges(saveBundle);
}
[HttpGet]
public IQueryable<Customer> Customers() {
return ContextProvider.Context.Customers;
}
For more information have a look to breeze documentation here.
Its seems like you are making a wrong Url Request. Look at your breeze route configuration for WebApi. You need to Pass like that http://localhost:53397/api/Values/Get as breeze is using Controller action based routing.
Hope this will help.