I have a web application which calls a DLL, this dll gets some of the data from a webservice. What I would like to do is when a user logs into the web app, i'm currently storeing it's username in a session variable. In my webService i have a WebMethod like this:
[WebMethod(EnableSession = true)]
public string getLoggedInUsername()
{
SessionManager session = new SessionManager();
return session.Username;
}
This works fine, however when i access the webservice from the DLL, the value returned is always NULL, this is because when the console app connects to the webservice a new session will be initialized. Is there any alternative how can i store the logged in username and pass it to the dll through my webservice? Using Application Get/Set is not a good decision since my webapp needs to handle different users. Anyone could point me in the right direction?
The SessionManager class contains the following:
public string Username
{
get
{
return (string)HttpContext.Current.Session["Username"];
}
set
{
HttpContext.Current.Session["Username"] = value;
}
}
after the user logs into my application (i'm using asp.net membership) : i assign the username to the session variable in this way:
SessionManager session = new SessionManager();
session.Username = User.Identity.Name;
Thanks.
Check this article: http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service
You may have to re-initialize the proxy and the cookie container
Related
I am trying to find an alternative to using a session variable. In my solution I have a project that is referenced by an ASP.NET web application and a console application. Both these applications can make changes to data and when a change is made the ID of the user making the change is logged against that row.
So if it was just the ASP.NET app making changes, it could do something like myObj.LastUpdatedByID = Session["userid"]. Given that the command line app needs to make changes and doesn't have a session, what alternative could I use that has the equivalent of session scope in ASP.NET but is also available in the console app scope?
I've had a look at MemoryCache, but that seems to be application level in ASP.NET.
I don't want to go down the line of passing the user ID through to each call.
Would doing something like checking for a HttpContext and if there is, pull from the session and if there isn't, pull from MemoryCahce? Or is there a better way of doing it?
EDIT:
The user ID is specifically set in the console app depending on what action is being carried. The console app is used for automated processes and there are numerous actions it undertakes. So for example, the sending email process would be carried out by user ID 1 and the delete old files process would be carried out by user ID 2. In some instances, the user ID would be set to the user ID that last made the change to that row of data.
EDIT:
Some example code (stripped for brevity). You can see I am using the MemoryCache here, which as I understand would be application wide and therefore not usable in ASP.NET app:
public class Base(
{
private int auditID = -1;
public int AuditID
{
get
{
if (this.auditID <= 0)
{
ObjectCache memCache = MemoryCache.Default;
this.auditID = ((int)memCache["CurrentUserID"]);
}
return this.auditID;
}
}
}
public class MyObject : Base
{
public int LastUpdatedByID { get; set; } = 0;
public bool Save()
{
bool b = false;
this.LastUpdatedByID = this.AuditID;
//Call to DB here...
return b;
}
}
If the data needs to be persistent across application then you can't use Session or HttpContext.Cache since those are dependent on current HttpContext which you don't have in console app.
Another way, would be to store the data in some persistent data store like Database or distributed cache like Redis Cache / Azure Mem Cache
I am in need of help with Web Api.
I am setting up a multi tenant system when each tenant has there own database of data using code first EF and web api (so that I can create multiple app platforms)
I have extended the standard ASP.NET Identity to include a client id and client model which will store all tenants and their users.
I have then created another context which tracks all the data each tenant stores.
Each tenant holds a database name which I need to access based on the authenticated user.
Not getting the user id from each api controller seems easy:
RequestContext.Principal..... etc then I can get the client and subsequently the client database name to pass to the database context however I am trying to implement a standard data repository pattern and really hate repeating myself in code yet the only way I see it working at the moment is to:
Application calls restful api after authorisation
Web Api captures call
Each endpoint gets the user id and passes it to the data store via the interface and subsequently into the data layer retrieving the database name for the context.
What I have a problem with here is each endpoint getting the user id. Is there a way to "store/track" the user id per session? Can this be achieved through scope dependency or something similar?
I hope that makes sense but if not please ask and I will try to clarify further, any help will be greatly appreciated.
Thanks
Carl
ASP WebApi does not have a session context. You may use a cookie or a request token identifier (pass this token back from login and use this token as a parameter for further API calls).
This is something I've developed some time ago. I'm simply creating a new class deriving from ApiController and I'm using this class as a base for all other API class. It is using the ASP.NET cache object which can be accessed via HttpContext. I'm using the current user-id as a reference. If you need something else, you may use another way of caching your data:
public abstract class BaseController: ApiController
{
private readonly object _lock = new object();
/// <summary>
/// The customer this controller is referencing to.
/// </summary>
protected Guid CustomerId
{
get
{
if (!_customerId.HasValue)
{
InitApi();
lock (_lock)
{
if (User.Identity.IsAuthenticated)
{
Guid? customerId = HttpContext.Current.Cache["APIID" + User.Identity.Name] as Guid?;
if (customerId.HasValue)
{
CustomerId = customerId.Value;
}
else
{
UserProfile user = UserManager.FindByName(User.Identity.Name);
if (user != null)
{
CustomerId = user.CustomerId;
HttpContext.Current.Cache["APIID" + User.Identity.Name] = user.CustomerId;
}
}
}
else
{
_customerId = Guid.Empty;
}
}
}
return _customerId.GetValueOrDefault();
}
private set { _customerId = value; }
}
// ... more code
}
Do not blame me on the "lock" stuff. This code was some kind of "get it up and running and forget about it"...
A full example can be found here.
Maybe I am far from truth but Web API is state less so you dont really have a session to track
I am using web browser control inside my application window application. is their any possibility to set or change session values through my application? is it possible to create or destroy session from windows application?
in web application i can create session using :
session("user")="loginUSer"
is their any similar process available in vb.net application?
There is no concept of Session in windows forms. You can create a static class. And then assigned a value to its variable when you want to log in.
Public static class login
{
public static string userId {get; set;}
}
login.userId = txtuserID.Text;
and set to null or empty string during log out.
U can set and remove the session variables in C#.net like
Session["UserID"] = UserID;
Session.Remove("UserID"); or Session["UserID"] = null;
And in VB.Net
Session("UserID") = UserID
Session.Remove("UserID") or Session("UserID") = Nothing
There's no need for "Session state" in a Windows application - you can store as much state in memory as you need. You can't directly set or remove session state values of a web application from your Windows app, but if you have access to the code for both, you could be crafty and have a 'hidden' page that you pass values to in the querystring to set or remove session state, i.e. 'http://mysite/sessionpage?variable=value'. Does this make sense ?
I need to store the current user name for every save request/user in SQL table. It is MVC 4 based application and hosted in IIS server. Also, it is an internal tool and NTLM based authentication.
I have got the username of current user using HttpContext.Current.User.Identity.Name My question is how the global variable reacts in MVC? What would happen for "currentUser" variable when multiple requests comes? Will the currentUser creates new value for every requests? Please help me to understand.
Sample Code:
public class ClearCacheController : ApiController
{
private string currentUser = HttpContext.Current.User.Identity.Name.ToLower();
public void method1()
{
SaveValue1(currentUser);
}
public void method2()
{
SaveValue2(currentUser);
}
public void method3()
{
SaveValue3(currentUser);
}
}
Controllers are instantiated and disposed for each unique request. So, something like User.Identity.Name is not really a global variable. It's an instance variable on the controller. (Well, User is an instance variable on the controller, while Identity is an instance variable on User, etc.). Long and short, it will only hold the value of the user who made the particular request being executed, not any user making any request.
Im thinking of getting usernames of my site using this in my view(Razor syntax):
#MySite.Helpers.Utils.UserName
heres the utils class:
public class Utils
{
static FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
public static string UserName { get { return id.Ticket.UserData; } }
}
Are there any potential problems with this code?
The reason Im doing it like this is because Im going to store username in the userdata field of a new FormsAuthenticationTicket when the user logs in.
I'm handling it like this because Im using facebook connect and want to store there ID in the username field in the db and their usernames/fullnames in a separate table.
so my logic to handle facebook usernames and my site registered usernames needs to be handled differently. Upon login Im thinking of handling it there then setting userdata as the actual username.
therefore throughout the site i can just get the logged in users name using : #MySite.Helpers.Utils.UserName
does this sound ok? will the fact that its a static variable be an issue?
or is there a better way to manage this? session variables maybe?
thanks
The reason Im doing it like this is
because Im going to store username in
the userdata field of a new
FormsAuthenticationTicket when the
user logs in.
The username of the currently logged in user is already stored in the authentication cookie. You don't need to store it once again in the UserData. And in order to retrieve it in your Razor template you could simply:
#User.Identity.Name
Obviously it is recommended to decorate the controller action rendering this view with the [Authorize] attribute to ensure that a user is authenticated before accessing it or you might get a NullReferenceException with this code.
As an alternative you could write a helper:
public static MvcHtmlString Username(this HtmlHelper htmlHelper)
{
var identity = htmlHelper.ViewContext.HttpContext.User.Identity;
if (identity.IsAuthenticated)
{
return MvcHtmlString.Create(identity.Name);
}
return MvcHtmlString.Empty;
}
which you could use like this:
#Html.Username()