I am writing an ASP.NET MVC 2 application and don't want to use ASP.NET Membership. I do want to use the Authorize attribute on the Controllers. What I have done so far is ...
Web.config
<roleManager enabled="true" />
<authentication mode="Forms">
<forms loginUrl="~/Authentication/Login" timeout="2880"/>
</authentication>
<authorization>
<allow users="*" /> /* This is for testing */
</authorization>
In my Global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
I am using a custom IIdentity so that I can add some custom properties in the future. To test this in my Controller action I did this ...
var testPrincipal = User;
I can see the custom Identity with all of the user information but there are no roles on principal object. Any help with what i have missed would be great. Thanks.
I believe you need a role provider. Much like how a Membership provider handles the membership of users, create, delete, validate, edit, in order to use roles, you need to use a RoleProvider (ASP.NET Implementing a Role Provider).
Which also requires enabling roles in the web.config, for example:
<roleManager enabled="enabled" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices"
applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider"
applicationName="/" />
</providers>
</roleManager>
This might be useful:
SO asp-net-mvc-roles-without-database-and-without-role-provider
As Might be:
ASP.NET 2.0, Custom Role assignment without a 'Role Provider'
UPDATE:
In the end I got this working by changing
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
to
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Thread.CurrentPrincipal = Context.User = tcmPrincipal;
}
Related
Behind an Azure API Management I have a bunch of APIs. All my applications are using an Identity Server 4 to validate and authenticate users and applications. When a request to the API comes, I like to validate the jwt token before proceeding.
For this reason , in the API Management, under the Security section, I selected OpenID connect and then my Identity Server.
In the design of the APIs, I added the validation-jwt
and the policy is like that
<policies>
<inbound>
<validate-jwt header-name="Authorization"
failed-validation-httpcode="401" require-scheme="Bearer"
output-token-variable-name="jwt">
<openid-config url="https://idsrv4/.well-known/openid-configuration" />
</validate-jwt>
<cors>
<allowed-origins>
<origin>*</origin>
</allowed-origins>
<allowed-methods preflight-result-max-age="300">
<method>GET</method>
<method>POST</method>
</allowed-methods>
<allowed-headers>
<header>*</header>
</allowed-headers>
<expose-headers>
<header>*</header>
</expose-headers>
</cors>
<base />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Then, in the Program.cs of my Blazor WebAssembly, I added the following code
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
string apiEndpoint = builder.Configuration["Api:EndpointsUrl"];
string apiScope = builder.Configuration["Api:Scope"];
builder.Services.AddScoped<APIService>();
#region Configure HTTP Client
builder.Services.AddHttpClient("companiesAPI", cl =>
{
cl.BaseAddress = new Uri(apiEndpoint);
})
.AddHttpMessageHandler(sp =>
{
var handler = sp.GetService<AuthorizationMessageHandler>()
.ConfigureHandler(
authorizedUrls: new[] { "https://localhost:7241" },
scopes: new[] { "220005_api" }
);
return handler;
});
builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("companiesAPI"));
#endregion
#region Configure Authentication and Authorization
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("oidc", options.ProviderOptions);
options.UserOptions.RoleClaim = "role";
})
.AddAccountClaimsPrincipalFactory<MultipleRoleClaimsPrincipalFactory<RemoteUserAccount>>();
builder.Services.AddAuthorizationCore();
#endregion
await builder.Build().RunAsync();
Finally, in the API service, I read the API.
public class APIService
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _options;
public APIService(HttpClient httpClient)
{
_httpClient = httpClient;
_options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
}
public async Task<APIResponse> GetAttributeAsync(APIRequest apirequest)
{
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"typing");
var content =
new StringContent(JsonSerializer.Serialize(apirequest),
Encoding.UTF8, "application/json");
request.Content = content;
HttpResponseMessage responseMessage;
responseMessage = await _httpClient.SendAsync(request);
responseMessage.EnsureSuccessStatusCode();
if (responseMessage.IsSuccessStatusCode)
{
var responseContent = await responseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<APIResponse>(responseContent, _options);
}
else
return new APIResponse() { Success = false };
}
catch (Exception ex)
{
return new APIResponse() { Success = false };
}
}
}
Now, if I call the API, I have the following error:
TypeError: Failed to fetch
If from the API Management, I remove the validate-jwt, the application calls the API and receives the answer with no issues.
What is the correct configuration for the API Management? What is the correct code in the Blazor project to pass the jwt token?
In your application code you should get the JWT like this
// This gets the UserToken (JWT) to get data from Microsoft Graph for the scopes: User.Read & Mail.Read
// scope for API: API/GUID [YOUR API-URL-FROM-YOUR-APPREGISTRATION-IN-AAD]
var token = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "User.Read", "Mail.Read", "api://12345678-1234-1234-1234-123456789012/products" });
In the APIM => In the Inbound you are missing the required claims
<inbound>
<validate-jwt header-name="Authorization"
failed-validation-httpcode="401"
failed-validation-error-message="Unauthorized. Access token is missing or invalid!!!">
<openid-config url="https://login.microsoftonline.com/11a14169-89cc-44e8-95d7-xxxxxxxxxxxx/v2.0/.well-known/openid-configuration" />
<required-claims>
<claim name="aud">
<value>{client-id-of-Client-API-1-on-App-Registration}</value>
</claim>
</required-claims>
Check your JWT over here to set the right claim for 'aud' in your APIM
Have a look at this question for more code details. The code is GOOD!
How do I get the JWT in a Blazor Server App with Microsoft Identity Platform (AAD) to make external API-Management call and authorize with the jwt
I am having trouble while sending the request to a rest service. The service works fine on my desktop, but getting the following error when i host on the IIS.
HTTP/1.1 400 Bad Request when i use https
HTTP/1.1 404 Not Found when i use http
Here is my web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service
behaviorConfiguration="CoreService.DialService.DialServiceBehavior"
name="CoreService.DialService.TelephonyService">
<endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="CoreService.DialService.ITelephonyService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CoreService.DialService.DialServiceBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true"/>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
maxMessagesToLog="3000" maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
Service Contract
[WebInvoke(UriTemplate = "/Dial", Method = "POST", RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Objects.Response.Telephony.DialResponse
Dial(Objects.Request.Telephony.DialRequest request);
Here is the client
DialRequest DialRequest = new DialRequest();
DialResponse DialResponse = new DialResponse();
DialRequest.ProjectID = "AMS0103300";
DialRequest.DialFromExtension = "1234";
DialRequest.OutDialCode = "51";
DialRequest.RequestBy = "HC User";
DialRequest.DialToPhoneNumber = "1234567890";
DialRequest.RequestDate = DateTime.Now;
DialRequest.ApplicationID = Guid.Parse("F5EE534B-B5ED-4ADD-B671-
CCF7C05057A7");
DataContractJsonSerializer ser =
new
DataContractJsonSerializer(typeof(Objects.Request.Telephony.DialRequest));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, DialRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
var result = webClient.UploadString("https://test.xxxx.com/DialService/TelephonyService.svc/Dial","POST", data);
I have tried with different values in protocolMapping, but the results are same. Any help will be appreciated.
It seems to me that there are no errors in you project. Besides protocol mapping is the new feature in Net4.5, which could help us simplify settings.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/simplified-configuration
How to make WCF Service Use HTTPS protocol
There might be some small problems during the process of hosting the service on the IIS.
Could you access the WSDL page successfully?
Like the following form.
We might need to enable the WCF feature in the control panel.
I have made an example, wish it is useful to you.
Server-side (WCF service application).
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[WebInvoke(UriTemplate ="/MyTest",Method ="POST",RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]
string Test(CompositeType compositeType);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
public override string ToString()
{
return $"The BoolValue is {boolValue}, StringValue is {stringValue}";
}
}
Service1.svc.cs
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public string Test(CompositeType compositeType)
{
return compositeType.ToString();
}
}
Web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="mybinding">
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
<add binding="webHttpBinding" scheme="https" bindingConfiguration="mybinding"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
IIS(new website)
Client(generate the data contract by adding service reference)
static void Main(string[] args)
{
//for validating the self-signed certificated.
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType()
{
StringValue = "Hello",
BoolValue = true
};
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceReference1.CompositeType));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, composite);
string data = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
WebClient webclient = new WebClient();
webclient.Headers["Content-type"] = "application/json";
webclient.Encoding = Encoding.UTF8;
var result = webclient.UploadString("https://localhost:8734/service1.svc/MyTest", "POST", data);
Console.WriteLine(result);
WebClient webclient2 = new WebClient();
webclient2.Headers["Content-type"] = "application/json";
webclient2.Encoding = Encoding.UTF8;
var result2 = webclient2.UploadString("http://localhost:8733/service1.svc/MyTest", "POST", data);
Console.WriteLine(result2);
}
Result.
Besides, PostMan is good choice to test Rest style service.
Feel free to let me know if the problem still exists.
I have a WCF REST service which accepts xml data as input and returns some data too. To implement Basic Authentication i use ServiceAuthorizationManager. The CheckAccessCore method calls twice automatically. In first call authorization header in CheckAccessCore is correct, but in second call authorization header is null.
ServiceAuthorizationManager CheckAccessCore method
protected override bool CheckAccessCore(OperationContext operationContext)
{
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
var credentials = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6))).Split(':');
var user = new
{
Name = credentials[0],
Password = credentials[1]
};
if (user.Name == "test" && user.Password == "pass")
{
return true;
}
else
{
return false;
}
}
else
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm =\"CreditData\"");
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
WCF Web.config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType="CreditDataService.Authorization.CreditDataAuthorizationManager, CreditDataService" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="CreditDataService.Services.CreditData" behaviorConfiguration="">
<endpoint name="REST" behaviorConfiguration="RestBehavior" binding="webHttpBinding" contract="CreditDataService.Contracts.ICreditData"/>
</service>
</services>
<protocolMapping>
<add binding="webHttpBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
Client
private void button4_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:33016/Services/CreditData.svc");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes("<Request><Firstname>John</Firstname><Lastname>Doe</Lastname><Pid>123456789</Pid></Request>");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.Method = "POST";
string credentials = "test:pass";
string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
string auth = string.Format("{0} {1}", "Basic", enc);
request.Headers[HttpRequestHeader.Authorization] = auth;
Stream reqStream = request.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream respStream = response.GetResponseStream();
string respStr = new StreamReader(respStream).ReadToEnd();
MessageBox.Show(respStr);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
}
MessageBox.Show(ex.Message);
}
}
Without ServiceAuthorizationManager it works correctly.
Problem was webservice's method's UriTemplate. It was empty and when i was calling service there was happening redirecting to the same url only with slash. e.g. when i sent request to "http://localhost/myservice.svc" it was redirected to "http://localhost/myservice.svc/". This arose second request and exactly this second request had Authorization header null. When i added UriTemplate problem solved.
I started a new project with EntityFramework 5.0 Code First with Automatic Migration and MVC4 with Simple Membership.
And I modified the Configuration.cs with the following:
protected override void Seed(UsersContext context)
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserID", "Username", true);
}
Console.WriteLine("Initialized websecurity");
CreateUser("admin");
CreateUser("radu");
CreateUser("mariana");
}
private static void CreateUser(string username)
{
if (!WebSecurity.UserExists(username))
{
WebSecurity.CreateUserAndAccount(username, "123456");
}
else
{
Membership.DeleteUser(username);
WebSecurity.CreateUserAndAccount(username, "123456");
}
}
Web.config entries look like this :
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
Error message: The user name or password provided is incorrect.
Unfortunately after a successfully migration when I try to log in with one of the users inserted in db, I get invalid log in message. Why is that and how should I fix this?
I have found the problems:
protected override void Seed(Handmade.Web.Models.UsersContext context) {
if (!WebSecurity.Initialized) {
//WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserID", "Username", true);
// I used wrong init for seed method
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", true);
}
Console.WriteLine("Initialized websecurity");
CreateUser("admin");
CreateUser("radu");
CreateUser("mariana");
}
private static void CreateUser(string username) {
if (!WebSecurity.UserExists(username)) {
WebSecurity.CreateUserAndAccount(username, "123456");
} else {
Membership.DeleteUser(username);
WebSecurity.CreateUserAndAccount(username, "123456");
}
}
Also corrected init from the filter attribute I used:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
//Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
I have many DBs in one SQL server.
I placed connectionString as template(look at Initial Catalog={0}) into web.config.
<add name="ent" connectionString="metadata=res://*/ent.csdl|res://*/ent.ssdl|res://*/ent.msl;provider=System.Data.SqlClient;provider connection string="Data Source=1.1.1.1;Initial Catalog={0};Persist Security Info=True;User ID=user;Password=pass;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
I want to create the objectContext with correct connectionString. I thought to do the following, CreatObjectContext<SiteEntities>('MySite') but I get error Unable to determine the provider name for connection of type 'System.Data.EntityClient.EntityConnection'.
public T CreatObjectContext<T>(string dbName) where T : ObjectContext, new()
{
var conStr = ConfigurationManager.ConnectionStrings["ent"].ConnectionString;
var entityBuilder = new EntityConnectionStringBuilder(conStr);
entityBuilder.Provider = "System.Data.SqlClient";
// Build correct conString to the db
entityBuilder.ProviderConnectionString = string.Format(entityBuilder.ProviderConnectionString, dbName);
var connection = new EntityConnection(entityBuilder.ConnectionString);
var builder = new ContextBuilder<T>();
return builder.Create(connection);
}
What I'm doing wrong? How I can create the context?
If you are using EntityConnectionStringBuilder, you only need to store the sqlserver connection strings in your web.config. EntityConnectionStringBuilder can then convert those to EF4 connection strings.
Example web.config
<connectionStrings>
<add name="db1" connectionString="data source=localhost\SQLEXPRESS;initial catalog=db1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework" />
<add name="db2" connectionString="data source=localhost\SQLEXPRESS;initial catalog=db2;integrated security=True;multipleactiveresultsets=True;App=EntityFramework" />
</connectionStrings>
And we can change your method to something like:
public ObjectContext CreatObjectContext(string dbName)
{
var conStr = ConfigurationManager.ConnectionStrings[dbName].ConnectionString;
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = conStr;
entityBuilder.MetaData = #"res://*/ent.csdl|res://*/ent.ssdl|res://*/ent.msl";
return new ObjectContext(entityBuilder.ToString());
}
I just wanted to share a small class to create an entity framework connection using the entity class as type of T an SQL connection string and the entityModel meta data name.
public static class EFConnection<T> where T : ObjectContext
{
public static T GetDatabase(string connectionString,string entityModelMetadataName)
{
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = connectionString;
entityBuilder.Metadata = #"res://*/" + entityModelMetadataName + ".csdl|res://*/" + entityModelMetadataName + ".ssdl|res://*/" + entityModelMetadataName + ".msl";
var _db=(T)Activator.CreateInstance(typeof(T), new object[] { entityBuilder.ToString()});
return _db;
}
}
use example:
var _db = EFConnection<Model1Container>.GetDatabase(Settings.General.Default.DatabaseConnectionString, "Model1");
I did use this post also to put everything together: