Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is the best way to persist a unique id on a browser session in MVC.NET?
Is there some session/cookie ID value by default?
In my Global.asax, I could create a new Session["ID"] and use its ID property.
There's got to be another way?
I tried using
var session = HttpContext.Current.Session;
UserResearch userResearch = new UserResearch();
userResearch.SessionID = sesstion.SessionID.ToString();
But i get an error:
System.NullReferenceException: Object reference not set to an instance of an object
I need to pull initial browser and clicking research based on a user that hasnt logged in to anything, so i need some way to refer to them, hence the id.
I could create a unique id on the sql end and store it in a session, just seems like there should be a more straight forward way.
Is there a browser session id?
Your problem most likely is caused by where in the code you are trying to access HttpContext, this is why your getting a NullReference for Session. But assuming you get that worked out this is how I'd approach your problem.
I would just store a GUID in a cookie, then Get/Set it like so: (Untested)
public Guid SessionGUID(){
if(HttpContext.Current.Request.Cookies["SessionGUID"])
{
//return the SessionGUID
return HttpContext.Current.Request.Cookies["SessionGUID"].value as Guid;
}
else//new visit
{
//set cookie to a new random Guid
var _guid=Guid.NewGuid();
HttpCookie guidCookie = new HttpCookie("SessionGUID");
guidCookie.Value = _guid;
guidCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(guidCookie);
return _guid;
}
}
As per https://stackoverflow.com/users/374310/igor: thanks!
global.asax is a file, class MvcApplication inside it may implement several methods/event handlers, some of those are called when Session is not available yet. Session_Start should work for you.
var session = HttpContext.Current.Session;
UserResearch userResearch = new UserResearch();
userResearch.SessionID = sesstion.SessionID.ToString();
I put it in Session Start and Voila!
Related
I'm currently working on a webserver in asp.net core.
I want the server to process the users input and data and am looking for a good solution to save complex Objects for the runtime.
So my first approach was to use Sessions. In Asp.net, sessions used to work like Session["key"] = new ValueObject()
In asp.net core however you can only use the methods SetString, SetInt32 and Set for byte arrays. I found a lot of solutions which basically converted the objects into Json strings. However in my case this isn't possible due to the objects containing other object references and more.
My second idea was to create a list of objects with the SessionId as identifier. Problem with this is that every time I would make request to the server, it needs to go through all existing Sessions to find the matching one, so this would probably drastically increase the time for the request.
So my question is what would be the best way to save user related objects?
Is using Sessions even the best way for solving this problem or am I missing something?
Note: Request are handled by JQuery AJAX, so reloading the page for accessing data is not an option.
You could try using the MemoryCache that can hold any .net type. It is not a problem but given it is a shared structure, it will be shared to all users, so, you have to carefull manage it. To do it, you could use HttpContext.Session.Id to define the keys on the memory cache instance. For sample (pseudo-code I didn't test):
public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
public async Task<IActionResult> CacheGetOrCreateAsynchronous()
{
string cacheKey = $"{HttpContext.Session.Id}_data";
var cacheEntry = await
_cache.GetOrCreateAsync(cacheKey , entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(3);
return Task.FromResult(DateTime.Now);
});
return View("Cache", cacheEntry);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Am just wondering how to solve this. I need to automate my company website. There I need to navigate more than one url for a multiple web pages. I have designed Hybrid framework along with Page object Model Design.
My Requirement is,
say I have 3 url's :
www.google.com
www.yahoo.com
Facebook
All the above url and its test data I will keep in an Excel sheet. I have created three different pages and three different test classes.
So my list of questions are:
How to pass url's one by one to [setup] method
how to call the test method deepening upon the url type
Execution Flow need to implement of Application:
You need to parametrize your test with TestCase attribute.
[TestCase("www.google.com")]
[TestCase("www.yahoo.com")]
[TestCase("www.facebook.com")]
public void WebPageTest(string site)
{
driver.Url(site);
//continue with the test.
}
See this article to learn more: https://github.com/nunit/docs/wiki/TestCase-Attribute
Storing URL in excel is not good idea,
You may store URL in app.config file and by using ConfigManager utility you may retrieve those URL from app.config file
As according to your test cases you can use URL where its needed and required
I would suggest you to use [category] attribute to categorise your test cases. For example
[Test]
[Category("GoogleTest")]
public void googletest1()
{
}
[Test]
[Category("FBTest")]
public void fbtest1()
{
}
Now in the [SetUp] method you can load url based on the category, something like
[SetUp]
public void testsetup()
{
#initialise driver
var category = TestContext.CurrentContext.Test.Properties.Keys;
if(category.Contains("GoogleTest"))
{
//category1 setup
}
else if(category.Contains("FBTest"))
{
//category2 setup
}
}
So using this method you can solve query # 2, i.e the url related to the test is already loaded for you, so you can continue with your tests after setup
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In my account controller I have something like this:
var result = await UserManager.CreateAsync(user, model.Password);
foreach (var error in result.Errors)
{
modelstateErrors.Add(error);
}
Every error string is localized in English language
What's the best practice in localizing ASP.NET Identity error messages?
Are there any libraries with localized errors, and how are they implemented?
Would it be good idea to switch on every ASP.NET Identity error and return your own localized string?
To localize ASP.Net Identity you need to install one of the following Nuget packages from the Nuget store => https://www.nuget.org/packages?q=Microsoft.AspNet.Identity.Core
You install the package that belong to your culture. So for French culture you should install Microsoft.AspNet.Identity.Core.fr
They all follow the pattern Microsoft.AspNet.Identity.Core.[Culture] where [Culture] is the code fo the culture.
Create e base controller and extend every controller from it
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// verify which kind of exception it is and do somethig like logging
}
}
It is one of the best practice por handlling errors, but for the localizing itself do what #codeNotFound said.
This question already has answers here:
Generating a new ASP.NET session in the current HTTPContext
(6 answers)
Closed 6 years ago.
I have such a requirement for my ASP.NET MVC app:
Session created before authentication should be closed and new session, with new ID, should be started
So it should work like this:
User is redirected (GET request) to my app (some method in the controller) with auth info
Closing old session, starting new one
Auth, saving user data to the session
Let's look to the controller:
public ActionResult Login(string token) {
Session.Abandon(); // I want new session!
// Some auth stuff
Session["this"] = "x";
Session["that"] = "y";
return View();
}
On debugging, i can see session values "this" and "that" set to "x" and "y". But now let's go the view that this method uses:
#{
var #this = Session["this"]; // Wut? #this is null
var that = Session["that"]; // Wut? that is null
}
So, a little digging gave me the answer:
Abandon causes the End event to be raised. A new Start event will be raised on the next request.
https://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon%28v=vs.110%29.aspx
It seems that lifecycle looks like this:
"Session.Abandon()" - session marked to be closed
Setting session values.
"return View()"
Session closed and (not sure about this) new session started
View - session values set in controller are missing.
Completly unacceptable. How can I overcome this?
I hope this code will solve your issue;
var XYZ= HttpContext.Current.Session["this"];
OR
You can use 'TempData' for your purpose.
var XYZ== TempData["this"].ToString();
these are the following technologies i am utilizing in my current project:
- WCF
- MVC 2
- Json
I'm just new with MVC 2 and Json. My question is, how do you pass values from a User Control back to the page where it was called?
Please answer my question or give me any reference links wherein i can extract ideas.
Thanks.
I suggest, Keep the user details in session when your user control finds a user. then access that session variable from your controller or any place of your application.
//After your user controller find the User
Session.add("userName",UserNameProperty);
from your controller//
if(Session("userName") != null){
string _uName = Session("userName").ToString()
// Do your logic
}