I'm currently using .NET Framework 4.5.1, I do not understand why 'name' seem to always not be present. I have tried
using Microsoft.AspNet.Identity
User.Identity.GetUserName()
Still I am getting the following compile time error stating on User that It does not contain in the current context?
Here is my create code
public void CreateRecord(SampleDataModel Rec)
{
DefaultConnection ent = new DefaultConnection();
SampleData dbRec = new SampleData();
dbRec.CreatedBy = User.Identity.GetUserName(); // <---- CAUSING ERROR
dbRec.CurrentOwner = Rec.CurrentOwner;
dbRec.DateOfBirth = Rec.DateOfBirth;
ent.SampleData.Add(dbRec);
ent.SaveChanges();
SampleData DummyObject = new SampleData();
CreateAuditTrail(AuditActionType.Create, dbRec.ID, DummyObject, dbRec);
}
Notice that User is a Member of the Page class.
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.user
So if your class, you are trying the get the User member doesn't derive from Page you cannot access it by simply writing User.
For example if it doesnt look like this:
public partial class _Default : Page
In this case you will have to use the more "direct" method and use
HttpContext.Current.User instead of only User
https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontext.user
So change your line from
dbRec.CreatedBy = User.Identity.GetUserName();
to
dbRec.CreatedBy = HttpContext.Current.User.Identity.GetUserName();
And add the namespace
using System.Web;
I believe that your problem is simply because your "User" isn't signed in.
Are you sure you have an authentification method ? (Usually a form.)
The reason could be that Anonymous Authentication is enabled for the application. Allow Windows (if it is in a domain) and disable Anonymous authentication.
In Visual Studio, open project properies
In IIS
Related
So at this point, I have two projects in my VS solution:
RecipeAPI, which is a ASP.Net Core Application
RecipeUI, which is a Windows Forms Application
Inside the RecipeAPI project, I already have the model and controller classes made and now I have to create a prototype UI in which the functionality should be implemented.
My issue is using the classes and objects from the API project, into the UI one. For example:
I am trying to populate a ListBox. Inside RecipeAPI, I have a controller class named RecipeController, which has the following method for retrieving data from the database:
[Route("v1/recipe/{recipeBy}")]
[HttpGet()]
public List<Recipe> GetRecipes(string recipeBy)
{
using (var con = _connFactory())
{
con.Open();
return con.Query<Recipe>("SELECT * FROM dbo.Recipe WHERE RecipeBy = #recipeBy", new { recipeBy }).ToList();
}
}
This was tested using PostMan, works perfectly fine. However, I am having huge issues trying to figure out how to populate the ListBox. In fact, I am having issues figuring out how I can use certain methods from a project to another. To be noted that I have already added references.
Moving forward, this is the method in the Forms class which is supposed to populate the ListBox.
private void ShowRecipes(string recipeBy)
{
List<Recipe> recipeList = new List<Recipe>;
recipeList = GetRecipes(recipeBy);
recipeListBox.DataSource = recipeList;
}
I am not entirely sure how correct this is. Basically what I am trying to do is get the list of recipes by calling the method GetRecipes() from RecipeController. Unfortunately, I am getting errors such as:
The type or namespace name 'Recipe' could not be found
The name 'GetRecipes' does not exist in the current context
So what am I missing here? Am I even on the right track or I shouldn't even try combining Web Forms and ASP.Core? And if this works too, then how can I be able to access methods from RecipeAPI.Controllers in RecipeUI Form?
You have to make Api Call to the RecipeAPI project from Windows Forms Application
in order to use the methods/logic of the APIs Project.
This is the way to make an API call:
How to make HTTP POST web request
I'm trying to follow the Bootstrap ServiceStack code from http://bootstrapapi.apphb.com/
I can register a new user, but soon I do everything I want (create a new user on my table that extends the UserAuth table) in the CreateUserAuth() method from my CustomUserAuth it redirects to http://localhost:50447/api/register
I want to go back to the Home Controller...
What is the simple way to accomplish this?
In the docs, under Authentication, this is not very explicit, and I'm using the latest version to date: v4.0.30 and I'm implementing a custom CredentialsAuthProvider.
You can use the ?Continue=/path QueryString parameter to specify where it should redirect to.
If you're using your own custom UserAuth tables (i.e instead of integrating with the existing UserAuth tables) you should subclass OrmLiteAuthRepository<T,T> class including your custom POCO's, e.g see the source for OrmLiteAuthRepository:
public class OrmLiteAuthRepository
: OrmLiteAuthRepository<UserAuth, UserAuthDetails>, IUserAuthRepository
{
public OrmLiteAuthRepository(IDbConnectionFactory dbFactory)
: base(dbFactory) { }
}
I have created a custom identity, principal and membership provider and accessing them through a UserContext class (all sitting in App_code):
public static class UserContext
{
public static CustomPrincipal User
{
get
{
return (CustomPrincipal)HttpContext.Current.User;
}
}
public static CustomIdentity Identity
{
get
{
return (CustomIdentity)HttpContext.Current.User.Identity;
}
}
}
From a controller class, I can do:
string userName = UserContext.Identity.Name;
However when doing the following from a view:
#Html.Encode(UserContext.Identity.Name)
I get the following error at run time:
The type 'Website.Infrastructure.UserContext' exists in both
'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\533b7079\25c5a39c\assembly\dl3\13397e32\308e247b_c8efce01\Website.DLL'
and 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\533b7079\25c5a39c\App_Code.-ze7s5wd.dll'
I have cleared out the temp/cache IISExpress folders, etc., ensured that I'm using System.Web v4.0.0, and have tried with adding the using [namespace] at the top of the shared layout view and in the relevant view's Web.config section.
Looking at the view, I'm seeing a compile error (suggestion?) under
UserContext
The type 'xxx' exists both in '[website root]' and 'App_Code' from a
MVC view
Suggestions?
Works fine. I notice that in your original description you add references to the views web.config. This is not correct and the views web.config <> to the web.config for the application.
add a reference to the utility project to the main web site
Build.
In your case take the references out of everywhere else in any of the other config files. I can make the project available to you if you like
I wanted to comment but I don't have enough points to comment so giving answer to this.
try to use full qualified class name like
Namespace.UserContext
, this might solve the conflict.
A simple question but I'd rather ask since I had problem with it two times.
I am trying to retrieve hostname from the url in ASP.NET project. The code is actually not in a web page but in a class (part of the domain). System.Web is included in the headers. When I try to use Request.QueryString it is not recognized. Even worse if I try HttpContext.Current, I get this error
'System.Web.HttpContext.Current' is null
Here is my code
using System.Web;
public class MyNightlyJob : AbstractJob
{
public override void ExecuteJob(IJobExecutionContext context)
{
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; // does not work
Request.ServerVariables["HTTP_HOST"]; // this does not work also
}
}
What am I missing? Note that my question is actually about Request.ServerVariables but if one works, the other will work too.
Note that Request.ServerVariable is not recognized in the code at all. HttpContext.Current is recognized but I get run time error for that.
You need to check if HttpContext.Current is a null. If it is null then its not in the right context to be retrieved.
If you can modify the function, I would pass the HttpContext.Current as a variable or pass the host as a variable.
The below code throws an error of "Object reference not set to an instance of an object" When calling mycache.Get("products"). Im using a WCF application. Im not 100% im using caching correctly. Any advice?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
namespace DataLayer {
public class Products
{
public List<Product> Current()
{
Cache mycache = new Cache();
if (mycache.Get("products")== null)
{
using (DataLayer.AccessDataContext db = new AccessDataContext())
{
var products = from p in db.fldt_product_to_supp_parts
where p.Current
select new Product
{
WholesaleCode = p.WholesaleCode,
ProductCode = p.Product_Code
};
mycache["products"] = products.ToList();
}
}
return mycache["products"] as List<Product>;
}
} }
EDIT : I'm using .net 3.5
I'm not sure what is wrong with your code, because I don't know off-hand how Cache is implemented, but a little searching uncovered the following Walkthrough from MSDN:
http://msdn.microsoft.com/en-us/library/dd997362.aspx
Caching Application Data in a WPF Application
And the following link gives an overview:
http://msdn.microsoft.com/en-us/library/dd997357.aspx
In summary, it appears that for .NET v4 onwards, caching has been moved into System.Runtime.Caching from System.Web.Caching.
From the look of the documentation you shouldn't be creating your own instance of the Cache class (it says the constructor is for framework use only). Try using Cache.Get instead?
EDIT (in response to comment)...
From the MSDN docs here:
One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.
So, it looks like Cache.Get is available when you're within a Page; otherwise you can call HttpContext.Cache to get the active cache. Either way, there's a single Cache object for your entire application and you definitely shouldn't be creating one of your own.
For non ASP.NET applications use caching from System.Runtime.Caching.
Your code throws System.NullReferenceException because internal cache CacheInternal of System.Web.Caching.Cache isn't initialized using internal void SetCacheInternal(CacheInternal cacheInternal) method. It initializes by ASP.NET infrastructure in System.Web.HttpRuntime class.
Unless I'm missing something, you're trying to use the ASP .NET cache within your WCF service. In order for this to work, you need to turn on ASP .NET compatibility using the AspNetCompatibilityRequirementsMode Enumeration. If you're self-hosting you'll have to roll your own.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class CalculatorService : ICalculatorSession
{
}