Web.config problems with Entity Framework - asp.net-mvc

New to asp.net when I go into the web.config I can't find the <entityframework> section in it to change some settings. I'm currently using this guide http://www.asp.net/mvc/overview/getting-started/introduction/getting-started to help me with my project. No idea what I've done wrong as I've followed each step.
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> <configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections> <connectionStrings>
<add name="LoftBook" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-LoftBook-20151211033930.mdf;Initial Catalog=aspnet-LoftBook-20151211033930;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> <appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5.1" />
</system.Web> --> <system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" /> </system.web> <system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules> </system.webServer> <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding> </runtime> </configuration>
using System;
using System.Collections.Generic;
using System.Linq; using System.Web;
using System.Data.Entity;
using LoftBook.Models;
namespace LoftBook.DAL {
public class LBInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<LBContext>
{
protected override void Seed(LBContext context)
{
var sires = new List<Sire>
{
new Sire {RingNo ="IHU S 2009 1143", Colour = "Blue", Breed = "Jassen",},
new Sire {RingNo ="IHU S 2011 1467", Colour = "Red", Breed = "Jan Arden",},
new Sire {RingNo ="IHU S 2012 2367", Colour = "Blue", Breed = "Jassen",},
};
sires.ForEach(s => context.Sires.Add(s));
context.SaveChanges();
var dams = new List<Dam>
{
new Dam {RingNo ="IHU S 2009 5362", Colour = "Blue", Breed = "Jassen",},
new Dam {RingNo ="IHU S 2011 9203", Colour = "Red", Breed = "Jan Arden",},
new Dam {RingNo ="IHU S 2012 2315", Colour = "Blue", Breed = "Jassen",},
};
dams.ForEach(s => context.Dams.Add(s));
context.SaveChanges();
var youngsters = new List<Youngster>
{
new Youngster {RingNo ="IHU S 2015 001", Colour = "Blue", Breed = "Jassen",},
new Youngster {RingNo ="IHU S 2015 002", Colour = "Red", Breed = "Jan Arden",},
new Youngster {RingNo ="IHU S 2015 003", Colour = "Blue", Breed = "Jassen",},
};
youngsters.ForEach(s => context.Youngsters.Add(s));
context.SaveChanges();
var pairs = new List<Pair>
{
new Pair {Sire = "IHU S 2009 1143", Dam = "IHU S 2009 5362", Paired = DateTime.Parse("2015-12-01"), Hatched = DateTime.Parse("2015-12-20"), Youngster = "IHU S 2015 001",},
new Pair {Sire = "IHU S 2011 1467", Dam = "IHU S 2011 9203", Paired = DateTime.Parse("2015-12-01"), Hatched = DateTime.Parse("2015-12-19"), Youngster = "IHU S 2015 002",},
new Pair {Sire = "IHU S 2012 2367", Dam = "IHU S 2012 2315", Paired = DateTime.Parse("2015-12-01"), Hatched = DateTime.Parse("2015-12-22"), Youngster = "IHU S 2015 003",},
};
pairs.ForEach(s => context.Pairs.Add(s));
context.SaveChanges();
}
} }
using System;
using System.Collections.Generic;
using System.Linq; using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using LoftBook.Models;
namespace LoftBook.DAL {
public class LBContext : DbContext
{
public LBContext()
: base("LBContext")
{
}
public DbSet<Dam> Dams { get; set; }
public DbSet<Sire> Sires { get; set; }
public DbSet<Pair> Pairs { get; set; }
public DbSet<Youngster> Youngsters { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
} }
Thanks in advance
Jason

First of all , I think you didn't add Entity framework to your project .
1.Install Entity First from Nuget Package Manager
2.Right click on Models in your project , then Add>New Item to add a database to your project
Here is the full guide for Get Start with Entity Framework
this article explain that you have designed a databse in sql server with diagrams and you want generate models from it (the easiest way that i tried before)

Related

Ionic 4 native http POST with multiple headers

Here is how I am doing an http post from my Ionic app:
import { HTTP } from '#ionic-native/http/ngx';
someAction(assetId: number, userId: number)
{
var asset: Asset = new Asset();
asset.assetId = assetId.toString();
asset.userId = userId.toString();
const options = {
headers: "Content-Type: application/json; charset=utf-8"
};
return this.http.post(this.url + "someAction", asset, options).then(data => {
return "Done";
}).catch(err => {
console.log(err);
});
}
According to the documentation here - https://www.npmjs.com/package/cordova-plugin-advanced-http#post, the headers should be sent like so:
headers: { 'content-length': '247' }
Which is not working for me. Note how I am sending the header key and value as one string:
headers: "Content-Type: application/json; charset=utf-8"
This is the error -
Error: advanced-http: header values must be strings
at checkKeyValuePairObject (helpers.js:88)
at checkHeadersObject (helpers.js:192)
at Object.handleMissingOptions (helpers.js:309)
at Object.sendRequest (public-interface.js:143)
at Object.post (public-interface.js:167)
at callCordovaPlugin (vendor.js:76774)
at vendor.js:76589
at vendor.js:76547
at new ZoneAwarePromise (polyfills.js:3268)
at tryNativePromise (vendor.js:76546)
I get the same error when trying to send multiple headers. I am at a loss as to why this is happening - the example in the documentation does not work! What am I missing?
Edit: web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<connectionStrings>
<add name="Default" connectionString="..." />
</connectionStrings>
<appSettings>
...
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" maxRequestLength="75096" executionTimeout="600" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Protocol.Extensions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.40306.1554" newVersion="1.0.40306.1554" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.8.1.0" newVersion="4.8.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering>
<verbs allowUnlisted="false">
<clear />
<add verb="GET" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="DELETE" allowed="true" />
<add verb="PUT" allowed="true" />
<add verb="OPTIONS" allowed="true" />
</verbs>
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<log4net>
...
</log4net>
</configuration>
Your headers should be an object:
const options = {
headers: {
'Content-Type': 'application/json'
}
};
Also, most likely you will need to enable CORS headers. Depending on your Web API version you can try one of this: Enabling CORS with WebAPI PUT / POST requests? or https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Cannot get MVC working in asp.net web forms project

I'm taking over a solution from a previous developer. In it are two projects. Both started as web forms. He added mvc to the one project and it works. I added mvc to the other one and no matter what I do I get 404s for all of my routing. I've compared everything I can think of between the two projects, spent the last day googling for an answer and can't figure out why it isn't working. This is running in visual studio 2017 with iisexpress, mvc 5.2.3.
Here's my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
</configSections>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd"></glimpse>
<system.web>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.6.1">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<identity impersonate="true" />
<httpRuntime maxRequestLength="30720" requestValidationMode="2.0"/>
<httpModules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" />
</httpModules>
<authorization>
<allow users="*" />
</authorization>
<customErrors mode="Off">
<error statusCode="404" redirect="~/Errors/PageNotFound.aspx" />
</customErrors>
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<tagMapping>
<add tagType="System.Web.UI.WebControls.CompareValidator" mappedTagType="Sample.Web.UI.Compatibility.CompareValidator, Validators, Version=1.0.0.0" />
<add tagType="System.Web.UI.WebControls.CustomValidator" mappedTagType="Sample.Web.UI.Compatibility.CustomValidator, Validators, Version=1.0.0.0" />
<add tagType="System.Web.UI.WebControls.RangeValidator" mappedTagType="Sample.Web.UI.Compatibility.RangeValidator, Validators, Version=1.0.0.0" />
<add tagType="System.Web.UI.WebControls.RegularExpressionValidator" mappedTagType="Sample.Web.UI.Compatibility.RegularExpressionValidator, Validators, Version=1.0.0.0" />
<add tagType="System.Web.UI.WebControls.RequiredFieldValidator" mappedTagType="Sample.Web.UI.Compatibility.RequiredFieldValidator, Validators, Version=1.0.0.0" />
<add tagType="System.Web.UI.WebControls.ValidationSummary" mappedTagType="Sample.Web.UI.Compatibility.ValidationSummary, Validators, Version=1.0.0.0" />
</tagMapping>
</pages>
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
<!-- Glimpse: This can be commented in to add additional data to the Trace tab when using WebForms
<trace writeToDiagnosticsTrace="true" enabled="true" pageOutput="false"/> -->
<httpHandlers>
<add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" />
</httpHandlers>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.1.0" newVersion="3.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000" />
</webServices>
</scripting>
</system.web.extensions>
</configuration>
Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*allaspx}", new { allaspx = #".*\.aspx(/.*)?" });
routes.IgnoreRoute("{*allasmx}", new { allasmx = #".*\.asmx(/.*)?" });
routes.IgnoreRoute("");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I finally got it working by adding this class to the Areas>API folder.
public class APIAreaRegistration : AreaRegistration
{
public override string AreaName => "API";
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"API",
"API/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}
}

Cookie Authentication can't maintains the login

I'm trying to make a way of the user stays logged in a website, but after some time (a couple of hours), the user needs to login again.
This is the code that I'm using:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromDays(30),
SlidingExpiration = true
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
#region Facebook Authentication
var facebookAuthenticationOptions = new FacebookAuthenticationOptions
{
AppId = Util.GetConfigValue("FacebookAppID"),
AppSecret = Util.GetConfigValue("FacebookAppSecret"),
SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
};
"email,user_about_me,user_birthday,user_hometown,user_location,user_website,user_relationships,user_mobile_phone"
.Split(',')
.ToList()
.ForEach(scope => facebookAuthenticationOptions.Scope.Add(scope));
facebookAuthenticationOptions.Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
var claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
app.UseFacebookAuthentication(facebookAuthenticationOptions);
#endregion
}
Here is the code of the AccountController:
// occurs when user authorize app in facebook
public async Task<ActionResult> Callback(string returnUrl)
{
var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
if (result == null || result.Identity == null)
{
TempData[Constants.ALERT] = "Error";
return RedirectToAction("Index", "Home");
}
// insert or update user info in database
var user = userService.GenerateUser(result.Identity.Claims);
if (!user.Active || user.IsLocked)
{
TempData[Constants.ALERT] = "Error";
return RedirectToAction("Index", "Home");
}
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = CreateClaimsIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
return RedirectToLocal(returnUrl);
}
private ClaimsIdentity CreateClaimsIdentity(User user, string authenticationType)
{
var result = new ClaimsIdentity(authenticationType, ClaimTypes.Name, ClaimTypes.Role);
result.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), "http://www.w3.org/2001/XMLSchema#string"));
result.AddClaim(new Claim(ClaimTypes.Name, user.Mail, "http://www.w3.org/2001/XMLSchema#string"));
result.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
result.AddClaim(new Claim("AspNet.Identity.SecurityStamp", Guid.NewGuid().ToString()));
result.AddClaim(new Claim(Constants.SUPER_USER, user.Super.ToString()));
return result;
}
and here the web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add name="QueroShowConn" connectionString="Data Source=..." providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="FacebookAppID" value="..." />
<add key="FacebookAppSecret" value="..." />
</appSettings>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/Error/NotFound" />
<error statusCode="403" redirect="/Error/Authentication" />
</customErrors>
<compilation targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<globalization enableClientBasedCulture="true" uiCulture="auto:pt-BR" culture="auto:pt-BR" />
</system.web>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="403"/>
<remove statusCode="404"/>
<error statusCode="403" responseMode="ExecuteURL" path="/Error/Authentication"/>
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
</httpErrors>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthenticationModule"/>
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNet.Identity.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Any ideias about what is going on?

how can I make Elmah.io integrate with my custom membership provider in asp.net MVC?

I installed Elmah.io properly but it doesnt work.
Visual studio gives 6 messages like; Could not find schema information for the element 'security' and 'errorlog' and 'elmah' and 'type' and logid and 'allowremoteaccess' .
how can i make it work?
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<connectionStrings>
<add name="deneme" providerName="System.Data.SqlClient"
connectionString="Data Source=THERMALTAKE\SQLSERVER2012;Initial Catalog=Tanimlama;Integrated Security=true;"/>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"/>
</authentication>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add name="CustomMembershipProvider" type="membership_kendiyazdigim.Security.CustomMembershipProvider" connectionStringName="deneme"
maxInvalidPasswordAttempts="5" applicationName="/" enablePasswordRetrieval="false" passwordAttemptWindow="10" requiresQuestionAndAnswer="false"
enablePasswordReset="true" requiresUniqueEmail="true" cacheTimeoutInMinutes="5"/>
</providers>
</membership>
<roleManager defaultProvider="CustomRoleProvider" enabled="true">
<providers>
<clear/>
<add name="CustomRoleProvider" type="membership_kendiyazdigim.Security.CustomRoleProvider" cacheTimeoutInMinutes="5"/>
</providers>
</roleManager>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
</httpModules></system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler"/>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler"/>
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler"/>
</modules>
</system.webServer><elmah>
<security allowRemoteAccess="false"/>
<errorLog type="Elmah.Io.ErrorLog, Elmah.Io" LogId="8b3ab986-ccfe-4099-ac3c-790942e77488"/>
</elmah><location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
</httpHandlers>
<!--
See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
more information on using ASP.NET authorization securing ELMAH.
<authorization>
<allow roles="admin" />
<deny users="*" />
</authorization>
-->
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode"/>
</handlers>
</system.webServer>
</location></configuration>
and this is my global logger filter...
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ElmahHandledErrorLoggerFilter());
}
}
public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if(context.ExceptionHandled)
{
ErrorSignal.FromCurrentContext().Raise(context.Exception);
}
}
}

MVC 5 Session Issue

Update 1: If i set the session via ajax request, this session is not available to me when the js does does a refresh of the current action. Now, if i setup a session via non ajax requests then these are available inside other controller even ajax actions as well.
Update 2: By removing and adding the session helped with this issue
<modules runAllManagedModulesForAllRequests="true">
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
I am setting up a new site, this uses forms authentication that i am validating against the active directory. On successful authentication, i put the user class in the session and it is available to me when i check it right away.
//login user and put the user in session
AuthenticationHelper.LoginUser(user, loginModel.IsRememberMe);
//just checking
var userFromSession = AuthenticationHelper.GetUserFromSession();
public static void LoginUser(User user, bool isRememberMe)
{
//login user and put user in the session
//log off first
LogOff();
//add user to session
AddUserToSession(user);
//sign in
if (!isRememberMe)
{
//Set cookie
FormsAuthentication.SetAuthCookie(user.UserId, false);
/*
GenericIdentity identity = new GenericIdentity(user.UserId);
string[] roles = { person.PersonaType };
GenericPrincipal principal = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principal;
*/
}
else
{
//Create Persistent cookie
var ticket = new FormsAuthenticationTicket(user.UserId, isRememberMe, 1);
var encrypted = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
authCookie.Expires = System.DateTime.Now.AddYears(1);
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Cookies.Add(authCookie);
}
}
}
public static void AddUserToSession(User user)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session["SignedInUser"] = user;
}
}
public static User GetUserFromSession()
{
User user = null;
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
user = (User) HttpContext.Current.Session["SignedInUser"];
}
return user;
}
However, when i refresh the page at the same very moment after login, my session is coming back as null. In this case Request.IsAuthenticated is true and User.Identity.Name has my user name in it.
I have the following in the web.config as well.
What am i missing here?
Here is the full web.config. Either i am missing something from the web.config or something is interfering with my session.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<!-- Move site specific app settings to their own environment config file inside Configs folder. Keep common settings here -->
<appSettings file="Configs\AppSettings_CurrentSprint.config">
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<machineKey validationKey="" validation="SHA1" decryption="AES" />
<sessionState mode="InProc" timeout="20" />
<authentication mode="Forms">
<forms loginUrl="~/EPT/Home" name="SalesSupport.ASPXFORMSAUTH" enableCrossAppRedirects="true" timeout="20" slidingExpiration="true" />
<!-- timeout="600" -->
</authentication>
<membership>
<providers>
<clear />
</providers>
</membership>
<profile>
<providers>
<clear />
</providers>
</profile>
<customErrors mode="Off" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="System.Web.Optimization" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<validation validateIntegratedModeConfiguration="false" />
<!--Had to set this for it to work on IIS 7-->
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<staticContent>
<!--Required to get IIS to compress javascript files-->
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
</staticContent>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Resources