I have an MVC 5 project with individual account auth, and two simple capture screens.

All was working fine, until I decided to grant a user a role on registration, so in the post action for Register, after UserManager.CreateAsync, if successful, I added:

 UserManager.AddToRoleAsync(user.Id, IdentityData.RoleNames.GeneralAdmin);

Then it threw SqlException: Invalid column name 'IdentityRoleId'.

Now it throws this exception any time I use UserManager, even UserManager.CreateAsync, before I have even tried to grant a role. The string IdentityRoleId does not occur anywhere in the project, and it was Identity that created its own tables, using the column name RoleId.

I must add that when I started the project, I had two DbContext classes, one with my business entities, and the auto-generated ApplicationDbContext, which has the Identity models deeply hidden somewhere. Yet even on decompiling this context, I see only RoleId in IdentityUserRoles.

A profiler traces shows this query, from where I have no idea - it's nowhere in my code. I expect it happens when a user is loaded, and that User's Roles are loaded:

exec sp_executesql N'SELECT 
    1 AS [C1], 
    [Extent1].[RoleId] AS [RoleId], 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[IdentityRoleId] AS [IdentityRoleId]
    FROM [dbo].[IdentityUserRoles] AS [Extent1]
    WHERE [Extent1].[UserId] = @p__linq__0',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'd299ba29-5266-40a2-b6cd-404588926a5b'

Where is this phantom IdentityRoleId coming from? Where should I look, or what should I do, to trace this down. Maybe the Microsoft.AspNet.Identity.EntityFramework is broken, or maybe EF is broken, but everything was working until that one change I made this morning, which is now completely deleted.

I have an ASP.NET application which relies heavily on AD authentication. We recently broke out a service which used to live in the same solution as the application into its own solution, so that we could maintain them seperately and not impact users who rely on the service when, say, we needed to make code changes which only impacted the UI side of the application.

This has lead to an interesting issue for me though. When I debug, I have my local copy of the application pointing to a remote instance of the service, which is also used by the environment copy of the application. When I attempt to authenticate user membership using the local app -> remote service call, it fails with the following exception:

System.Runtime.InteropServices.COMException (0x8007200A): The specified directory service attribute or value does not exist.

at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_SchemaEntry() at System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry de) at System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry ctxBase, Boolean ownCtxBase, String username, String password, ContextOptions options) at System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry) at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) at ******************.******************.******************.IsUserMemberOfGroup(String userName, String groupName)

When I attempt to authenticate the same user in the same group, but using a web browser to hit the app on the remote box which then hits the remote service, it's happy as a clam.

The code I'm using seems trivially simple. It must be something to do with how my machine is calling out, but I'll be dipped if I can work it out.

public static bool IsUserMemberOfGroup(string userName, string groupName)
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "XXX");

        var user = GetUser(userName, ctx);

        if (user == null)
            Log4NetLogManager.LogError("Unable to find user " + userName);
            return false;

        // find the group in question
        groupName = groupName.Replace("XXX\\", string.Empty);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);

        if (group != null) return user.IsMemberOf(group);

        Log4NetLogManager.LogError("Unable to find group " + groupName);
        return false;
    catch (Exception ex)
        if (!ex.Message.Contains("Unknown error"))
            Log4NetLogManager.LogException(string.Format("Error while checking if {0} is a member of {1}", userName, groupName), ex);
        return false;

private static UserPrincipal GetUser(string userName, PrincipalContext ctx)
    UserPrincipal user = null;
    userName = userName.Replace("XXX\\", string.Empty);

        user = UserPrincipal.FindByIdentity(ctx, userName);

    return user ?? UserPrincipal.FindByIdentity(ctx, userName);

I have way too many pages in the application that basically load the same set of xml and js files for client side interaction and validation. So, I have about dozen lines like this one <script type="text/javascript" src="JS/CreateMR.js"></script> or like this one <xml id="DefaultDataIslands" src="../XMLData/DataIslands.xml">.

These same files are included in every page and as such browser sends request to read them every time. It takes about 900ms just to load these files.

I am trying to find a way to load them on just the login page, and then use that temp file as source. Is it possible to do so? If yes, how and where should I start?

P.S. A link to a tutorial will work too, as I have currently no knowledge about that.


I can't cache the whole page, because the pages are generated at runtime based on the different possible view modes. I can only cache the js and xml file. Caching everything might be a problem.

Anyway, I am reading through the articles suggested to figure out how to do it. So, I may not be able to accept any answer right away, while I finish reading and try to implement it in one page.

Edit: Turns out caching is already enabled, it is just that my server is acting crazy. Check the screenshot below.

With Cache With cache (304 response)

Without cache Without cache (200 response)

As you see, with cache, it is actually taking more time to process some of the requests. I have no idea what that problem is, but I guess I should go to the server stack exchange to figure this out.

As for the actual problem, turns out I don't have to do anything to enable caching of xml and js files. Had no idea browsers automatically cache js files without using specific tag.

I've built a RESTful API (using ASP.NET Web API 2) which is only meant to be consumed from a single end-point. This end-point is a basic front-end site containing only HTML/CSS/JS. Due to various reasons, the front-end site and the API are completely external from one-another, with the front-end site being whitelisted in the API's CORS configuration.

I'm now trying to lock-down the API so that it's only accessible from this particular end-point, without introducing a new login system, because the context of where this page lives ensures that anyone accessing it is already a trusted user (it's technically behind a login system, but the page consuming the API has almost no knowledge of this context).

At a high level, I'd like to introduce a statically defined API Key of some sort, that would be hardcoded into both the API and the JavaScript of the consuming page, to help ensure that it's the only end-point accessing the API. We can assume that all communications between the front-end page and the API will be over a secure SSL/TLS connection.

My question: for such a case where I want to authenticate API requests from a particular page with a statically-defined API Key, what would be my best option from an ease-of-implementation standpoint? Most of the articles that I've found on Web API Authorization pivot around a user login system and seem grossly over-engineered for my particular use-case. I'd consider myself a novice when it comes to the subject and so I'm really just hoping for someone to point me in the right direction.


HttpContext.Session["list"] = new List<object> { new object(), new object() };

I want to add a new object to this session, how to achieve this??

I want to open a .tif file from web server with default explorer on client machine, I've almost seen all related questions but still confused whether it is possible or not.

Here's the code line that ends up throwing Access Denied error:


I've also tried this:


this results no error but no response either.

(both are working well on localhost, having trouble when uploading it to the web server and running on IIS)

Any help on the topic or an alternative solution to view .tif file will be appreciated.

So I have this code that sets a session and redirects to another page:

Protected Sub LoginButton_Click(sender As Object, e As EventArgs)

    Dim CredentialsValid = Membership.ValidateUser(UserName.Text, Password.Text)

    If (CredentialsValid) Then
        'Add User Session stuff
        Session.Add("MFUserName", UserName.Text)
        Session.Add("MFPW", Password.Text)
        Response.Redirect("MFACheck.aspx", False)

    End If

End Sub

When stepping through the code, I land on MFACheck.aspx, which has this code behind:

Public Class MFACheck

Inherits System.Web.UI.Page

Dim UserName = Session.Item("MFUserName")
Dim pw = Session.Item("MFPW")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

I am getting an error when I hit this line in MFACheck.aspx

 Dim UserName = Session.Item("MFUserName")

The error states that

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

The problem is that I seem to satisfy each of these requirements. Here is the page directive on MFACheck.aspx

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/NoNav.Master" CodeBehind="MFACheck.aspx.vb" Inherits="REDACTEDFORSOPOST" EnableSessionState="true" %>

Also, under system.web in my web.config, I have this:

        cookieless ="false"/>

And under system.webServer, I have this

  <remove name="Session" />
  <add name="Session" type="System.Web.SessionState.SessionStateModule"/>

What am I missing? I seem to have all of the requirements to read my session on MFACheck.aspx, why does the page give me an error?

Thank you for your help/

When registering an account through Web API with an email such as "xxx-yyy@gmail.com", Fiddler returns the follow error. Note that email is used for username as well, so both fields are the same. But it works when registering on MVC itself.

ExceptionMessage=User Creation Failed - Identity Exception. Errors were:

User name xx-yyy@gmail.com is invalid, can only contain letters or digits.

User Object

 var newUser = new ApplicationUser {
            UserName = user.Email,
            Email = user.Email


public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager) {
            RequireUniqueEmail = true,
            AllowOnlyAlphanumericUserNames = false


I have tried commenting out AllowOnlyAlphanumericUserNames but it didn't work. By right setting it to false should allow special characters, in my case a hyphen(-).

API Controller

// POST: api/auth/register
    public async Task<HttpResponseMessage> PostRegister(Auth user) {

        //dash issue is here. 

        var userContext = new ApplicationDbContext();

        var userStore = new UserStore<ApplicationUser>(userContext);

        var userManager = new UserManager<ApplicationUser>(userStore);

        var newUser = new ApplicationUser {
            UserName = user.Email,
            Email = user.Email

        var result = await userManager.CreateAsync(newUser, user.PasswordHash);

        if (result.Succeeded) {

There are two pages: Login.aspx and Profile.aspx, which are built using HTML and AngularJS.

The login.aspx page uses ng-view to get the template of Login-view or Signup View. The code used is:

    <base href="/Login.aspx" />
    <link href="StyleSheet/Login_css.css" rel="stylesheet" />
    <script src="JscriptVendors/angular.min.js"></script>
<body ng-app="JouralApp_login">
    <div ng-view></div>

    <script src="Jscript_Angular/Model.js"></script>
    <script src="Jscript_Angular/Controllers/LoginPageController.js"></script>
    <script src="JscriptVendors/angular-route.min.js"></script>
    <script src="JscriptVendors/angular-animate.min.js"></script>
    <script src="JscriptVendors/jquery.min.js"></script>

The views are stored in Template folder with the names as: loginTemplate.html, and signupTemplate.html.

The module used for handling the login.aspx page is:

var app_login = angular.module('JouralApp_login', ['ngRoute','ngAnimate']);
var app_profile = angular.module('GameApp', []);

app_login.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
        .when('/login', {
            templateUrl: 'Jscript_Angular/Templates/loginTemplate.html',
            controller: 'loginController'
        .when('/signup', {
            templateUrl: 'Jscript_Angular/Templates/signupTemplate.html'

Now a created my Profile.aspx, with the HTML code as:

    <script src="Scripts/angular.js"></script>
<body ng-app="app_profile">    
    <div ng-controller="chatController">
            <div ng-repeat="chat in messages">{{chat}}</div>
                <input type="text ng-model="message" />
                <input type="button" ng-click="newMessage()" />
    <script src="Jscript_Angular/Model.js"></script>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="signalr/hub"></script>
    <script src="Jscript_Angular/Controllers/ChatController.js"></script>

Every thing was working fine until I try to integrate SignalR into my project. I made two classes:


[assembly: OwinStartup(typeof(Startup))]

public class Startup
    public void Configuration(IAppBuilder app)


public class ChatHub : Hub
    public void SendMessage(string name, string message)
        Clients.All.broadcastMessage(name, message);

I also made the following controller in order to access my javascript function:

app_profile.controller('chatController',['$scope', function ($scope) {
    $scope.name = 'Guest';
    $scope.message = '';
    $scope.messages = [];
    $scope.chatHub = null;

    $scope.chatHub = $.connection.chatHub;

    $scope.chatHub.client.broadcastMessage = function (name, message) {
        var newMessage = name + "    " + message;

    $scope.newMessage = function () {
        $scope.chatHub.server.sendMessage($scope.name, $scope.message);
        $scope.message = '';

Now when I try to access my profile page, it show the error

angular.js:13550 Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .

Also when i try to access, localhost:5136/signalr/hubs, it redirects me to my login page, i.e: localhost:5136/login

I think the problem is that, it cannot access the hub which I created because of the routing which i did using angularJS for the login page.

Please help me find the solution.

I would like my JSON element returned by my controller to look like this

              "model": "Ford",
              "make": "GT350R",
              "dealerName": "Dallas Ford",
              "location": {
                  "dealerName": "Dallas Ford",
                  "zip": 05700,

I cant seem to get the query right in my controller. I want to select all rows and every element from the Cars Model and where there is a foreign key to the location Table. I then want to embed all the rows that belong to that location element into a sub element. I think i may need to tell my models about the foreign key but because i am using the same attribute name i think Entity Framework 6 does it for me.

This is the code I am trying which will only select all the results from Cars it wont show the location as a nested element.

var query = (from results in db.Cars
                 join location in db.Locations on results.DealerName equals location.Dealername
                 select results                          
                return Ok(query.ToList());

This is the json that it shows for each element

{ "model": "Ford", "make": "GT350R", "dealerName": "Dallas Ford", }

Here are my models

Car model

    public string make { get; set; }
    public string model { get; set; }
    public string dealerName { get; set; }

Location model

    public string dealername{ get; set; }
    public string Zip { get; set; }

And heres what i think the code should look like but I am not doing it right.

 var query = (from results in db.Cars
                 join location in db.Locations on results.DealerName equals location.Dealername
                 select new{
                   results = results;
                   results.location = location;
                return Ok(query.ToList());

I would like to create a web api project and the response depend of request "apiVesion" parameter. How could I return the response depending of that parameter? For example:

if the apiVersion = 1 return /controllers/v1/response.cs

then if the apiVersion = 2 return /controllers/v2/response.cs

I have the following code:

 <asp:Button ID="btnDelete" runat="server" Text="Delete Report"   OnClientClick="return confirm ('This will delete the report.  Continue?');" OnClick="btnDelete_Click" />

 protected void btnDelete_Click(object sender, EventArgs e)
   // I have code here but it never fires


Once the user clicks on OK how do I get the server side script to fire that actually deletes.

I know how to send email via c# but i have a problem i am sending the email with certain credentials and the email is being sent from my account to my account i mean the user accesses the website and enters his email and other info and send the message to me but it's sent from me also because of the authentication needed to access gmail... what i have is that the user must send his email and i need to reply to his email so he may send his email incorrectly and i will receive a mail sent by him but from my account and might not be able to get his email because he entered this info incorrectly... what i have in mind to fix this is to let the user retype his email and if both textboxes match then he can send the message otherwise he'll get an error message.. is this a good idea to fix this or can anyone help me getting a better one? thanks.

I have such a code ng-init="validationRegex = '@RegularExpression.expression'" where RegularExpression.expression is c# string variable = "(\w+\/|\w+\\)+(\w+)\.\w+". I want to pass variable value to angular controller using ng-init. But in the end I get (w+/|w+\)+(w+).w+. How can I get right value?

Our security team wants me to disable debugging on an ASP.NET site that I have developed. They object to the server sending responses in response to a DEBUG request.

I have disabled debugging in the web config file using the tag.

I see that there are several machine.config and machine.config.default files on the server, and I have set retail="true" for the deployment tag in all of them, and the configuration editor in EES shows the retail attribute as true.

Still, when I point curl --trace - at my site, I still get trace information.

What else do I need to do?

I need a regex to exclude specific chars.



I'm trying to redirect with this code:

  protected void btnLogin_Click(object sender, EventArgs e)
        User user = ConnectionClass.LoginUser(txtUsername.Text, txtPassword.Text);

        if (user != null)
            //Store login variables in session
            Session["login"] = user.Username;
            Session["user_type"] = user.Type;

            var userType = (string)Session["user_type"];
            if (userType == "user" && userType == "special_user")

            lblError.Text = "Login Failed";


that is suppose to redirect me to another web page,but the code do not redirect at all.

I want to display Timer on Page layout header. it should be according to user time zone. "plz help " How to show timer after user logged?

I'm trying to make a private message system.

What I have so far. - checking if player exists with the name from textbox, if not, error shows up.

Now, I'm trying to insert it to the table. The problem is that the table have 2 colums


And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.

this is my code

      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
    SqlCommand cmdd = new SqlCommand();
    cmdd.CommandText = "select * from [users]";
    cmdd.Connection = conn;

    SqlDataReader rd = cmdd.ExecuteReader();

    while (rd.Read())
        if (rd[1].ToString() == TextBox_To.Text)
            flag = false;

    if (flag == true)
        Label1.Visible = true;
        Label1.Text = "User does not exist";

    else if(flag == false)

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = con;

            cmd.CommandText = @"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date) 
                                VALUES (@title, @content, @to, @from, @date)";

            cmd.Parameters.AddWithValue("@title", TextBox_Title.Text);
            cmd.Parameters.AddWithValue("@content", TextBox_Msg.Text.Replace("\n", "<br/>"));
            cmd.Parameters.AddWithValue("@to", TextBox_To.Text);
            cmd.Parameters.AddWithValue("@date", DateTime.Now);
            cmd.Parameters.AddWithValue("@from", Session["id"].ToString());




Of course I got an error

Conversion failed when converting the nvarchar value 'username' to data type int.


@cordan I tried this

DECLARE @user_id = (SELECT id FROM users WHERE user_login=@to ); 
                                    INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date) 
                                    VALUES (@title, @content, @user_id, @from, @date); 
                cmd.Parameters.AddWithValue("@to", TextBox_To.Text);

got this error

 Incorrect syntax near '='.
Must declare the scalar variable "@user_id".

I have a website which i'm planning to close down and replace with another with a different domain, how can i go about setting up 301 redirects from specific pages on my old site to the relevant pages on my new one?

I've had a look into the IIS Url Rewrite Module, but wasn't able to figure it out. Help please?

Hey guys I'm making a web application and I'm having a problem in a certain page (Search.aspx). When the locale is on default the page loads and works perfectly but when I change the language the page continues to load for about a minuet HTML controls do not respond and finally the page crashes. There are no error messages and no resx files related to the page. Can anybody help? I have a theory about sessions/cookies but I have no idea how to find the problem exactly.