Authentication and Authorization in Web API -Part1
The Authentication technique used mainly by token based with OWIN, Step was to register a user , We created a appliction form to submit the user credentials to the WEB API Post Mehtod and saved in the database . We have built a repository class which interacts with the database and gives the required result-set when requested for , We have also introduced a Business Layer which handles the business logics and acts as model for the controller . The implementations of the Authentication and Authorization is done from this site .
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
The Controller Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;
namespace WebApiDemo.Controllers
{
public class EmployeeController : ApiController
{ [Authorize]
[HttpGet]
public IEnumerable<Employee> GetEmployee()
{
BusinessLayer b = new BusinessLayer();
return b.getEmployees();
}
/*
* Test U-http://localhost:8322/api/Employee/GetEmployee?gender=female
* U-http://localhost:8322/api/Employee/GetEmployee?gender=male
* U-http://localhost:8322/api/Employee/GetEmployee?gender=all
*
* */
[Authorize]
[HttpGet]
public HttpResponseMessage GetEmployee(string gender)
{
try
{
BusinessLayer bl = new BusinessLayer();
switch(gender.ToLower())
{
case "all":
{
return Request.CreateResponse(HttpStatusCode.OK,bl.getEmployees().ToList());
}
case "female":
{
var emp = bl.getEmployees().Where(Row => Row.gender == "Female").ToList();
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
case "male":
{
var emp = bl.getEmployees().Where(Row => Row.gender == "Male").ToList();
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Values must be All,male,female " + gender + " is invalid");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
[Authorize]
[HttpPost]
public HttpResponseMessage PostEmployee([FromBody]Employee emp)
{
BusinessLayer b = new BusinessLayer();
string result;
try
{
result=b.postEmployee(emp);
if(result=="Failure")
{
throw new Exception();
}
var message = Request.CreateResponse(HttpStatusCode.Created, emp);
message.Headers.Location = new Uri(Request.RequestUri + emp.Id.ToString());
return message;
}
catch (Exception e)
{
var message = Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
}
}
[Authorize]
[HttpDelete]
public HttpResponseMessage DeleteEmployee(int Id)
{
try
{
BusinessLayer b = new BusinessLayer();
var emp = b.getEmployees().Where(x => x.Id == Id).Select(v=> v.firstName).ToList();
if (emp.Count == 0)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, " EmployeeId " + Id.ToString() + " do Not Exists");
}
else
{
b.deleteEmployee(Id);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
}
}
/*
Testing : {"Id":1,"firstName":"Hari","lastName":"Singh","gender":"female","Salary":25000} Json value to be sent from FormBody
* {"email":"amit.mazumder@sbc.com","password":"hello","confirmPassword:"hello" }
*/
//[Authorize]
[HttpPut]
public HttpResponseMessage Put(int Id,[FromBody]Employee emp)
{
try
{
BusinessLayer bl = new BusinessLayer();
var em = bl.getEmployees().Where(row => row.Id == Id).Select(v => v.firstName).ToList();
if (em.Count == 0)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Id" + Id.ToString() + "Do not Exists");
}
else
{
bl.UpdateEmployee(Id, emp);
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
[HttpPost]
public HttpResponseMessage Register([FromBody]RegisterModel emp)
{
try
{
BusinessLayer b = new BusinessLayer();
b.RegisterUser(emp);
return Request.CreateResponse(HttpStatusCode.OK, "User " + emp.email + " added");
}
catch(Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
}
}
}
}
Repository layer class - which interacts with the database
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/*
Data Source=APOTHEOSIS113\SQLEXPRESS;Initial Catalog=WebApiDb;Integrated Security=True;Pooling=False
*/
namespace WebApiDemo
{
public class RepositoryLayer
{
public DataTable getEmployee()
{
String cs=ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("Select * from Employee", conn))
{
conn.Open();
SqlDataAdapter ap = new SqlDataAdapter(cmd);
ap.Fill(dt);
}
}
return dt;
}
public string postEmployee(int param1,string param2,string param3,string param4,int param5)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command="insert into Employees values ("+ param1+",'"+param2+"','"+param3+"','"+param4+"',"+param5+")";
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
conn.Open();
try
{
cmd.ExecuteNonQuery();
return "Success";
}
catch(Exception e)
{
return "Failure";
}
}
}
}
public void deleteEmployee(int Id)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command = "delete from Employee where Id=" + Id;
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
public void UpdateEmployee(int param1, string param2, string param3, string param4)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command = "Update Employee Set First_Name='" + param2 + "' ,Last_Name='" + param3 + "' ,Gender='" + param4 + "' where Id=" + param1;
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
public void registerEmployee(string param1, string param2, string param3)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
SqlConnection conn=new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Register_User", conn);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("Email",param1));
cmd.Parameters.Add(new SqlParameter("Password", param2));
cmd.Parameters.Add(new SqlParameter("ConfirmPassword", param3));
try
{
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception Ex)
{
throw Ex;
}
}
public DataTable getUser(string email, string password)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
DataTable dt = new DataTable();
string commad="select * from [User] where Email='"+email+"' and Password='"+password+"'";
using (SqlConnection conn = new SqlConnection(cs))
{
using(SqlCommand cmd= new SqlCommand(commad,conn))
{
conn.Open();
try
{
SqlDataAdapter ap = new SqlDataAdapter(cmd);
ap.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
}
}
return dt;
}
}
}
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
The Controller Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;
namespace WebApiDemo.Controllers
{
public class EmployeeController : ApiController
{ [Authorize]
[HttpGet]
public IEnumerable<Employee> GetEmployee()
{
BusinessLayer b = new BusinessLayer();
return b.getEmployees();
}
/*
* Test U-http://localhost:8322/api/Employee/GetEmployee?gender=female
* U-http://localhost:8322/api/Employee/GetEmployee?gender=male
* U-http://localhost:8322/api/Employee/GetEmployee?gender=all
*
* */
[Authorize]
[HttpGet]
public HttpResponseMessage GetEmployee(string gender)
{
try
{
BusinessLayer bl = new BusinessLayer();
switch(gender.ToLower())
{
case "all":
{
return Request.CreateResponse(HttpStatusCode.OK,bl.getEmployees().ToList());
}
case "female":
{
var emp = bl.getEmployees().Where(Row => Row.gender == "Female").ToList();
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
case "male":
{
var emp = bl.getEmployees().Where(Row => Row.gender == "Male").ToList();
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Values must be All,male,female " + gender + " is invalid");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
[Authorize]
[HttpPost]
public HttpResponseMessage PostEmployee([FromBody]Employee emp)
{
BusinessLayer b = new BusinessLayer();
string result;
try
{
result=b.postEmployee(emp);
if(result=="Failure")
{
throw new Exception();
}
var message = Request.CreateResponse(HttpStatusCode.Created, emp);
message.Headers.Location = new Uri(Request.RequestUri + emp.Id.ToString());
return message;
}
catch (Exception e)
{
var message = Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
}
}
[Authorize]
[HttpDelete]
public HttpResponseMessage DeleteEmployee(int Id)
{
try
{
BusinessLayer b = new BusinessLayer();
var emp = b.getEmployees().Where(x => x.Id == Id).Select(v=> v.firstName).ToList();
if (emp.Count == 0)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, " EmployeeId " + Id.ToString() + " do Not Exists");
}
else
{
b.deleteEmployee(Id);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
}
}
/*
Testing : {"Id":1,"firstName":"Hari","lastName":"Singh","gender":"female","Salary":25000} Json value to be sent from FormBody
* {"email":"amit.mazumder@sbc.com","password":"hello","confirmPassword:"hello" }
*/
//[Authorize]
[HttpPut]
public HttpResponseMessage Put(int Id,[FromBody]Employee emp)
{
try
{
BusinessLayer bl = new BusinessLayer();
var em = bl.getEmployees().Where(row => row.Id == Id).Select(v => v.firstName).ToList();
if (em.Count == 0)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Id" + Id.ToString() + "Do not Exists");
}
else
{
bl.UpdateEmployee(Id, emp);
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
[HttpPost]
public HttpResponseMessage Register([FromBody]RegisterModel emp)
{
try
{
BusinessLayer b = new BusinessLayer();
b.RegisterUser(emp);
return Request.CreateResponse(HttpStatusCode.OK, "User " + emp.email + " added");
}
catch(Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
}
}
}
}
Repository layer class - which interacts with the database
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/*
Data Source=APOTHEOSIS113\SQLEXPRESS;Initial Catalog=WebApiDb;Integrated Security=True;Pooling=False
*/
namespace WebApiDemo
{
public class RepositoryLayer
{
public DataTable getEmployee()
{
String cs=ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("Select * from Employee", conn))
{
conn.Open();
SqlDataAdapter ap = new SqlDataAdapter(cmd);
ap.Fill(dt);
}
}
return dt;
}
public string postEmployee(int param1,string param2,string param3,string param4,int param5)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command="insert into Employees values ("+ param1+",'"+param2+"','"+param3+"','"+param4+"',"+param5+")";
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
conn.Open();
try
{
cmd.ExecuteNonQuery();
return "Success";
}
catch(Exception e)
{
return "Failure";
}
}
}
}
public void deleteEmployee(int Id)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command = "delete from Employee where Id=" + Id;
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
public void UpdateEmployee(int param1, string param2, string param3, string param4)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
string command = "Update Employee Set First_Name='" + param2 + "' ,Last_Name='" + param3 + "' ,Gender='" + param4 + "' where Id=" + param1;
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(command, conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
public void registerEmployee(string param1, string param2, string param3)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
SqlConnection conn=new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Register_User", conn);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("Email",param1));
cmd.Parameters.Add(new SqlParameter("Password", param2));
cmd.Parameters.Add(new SqlParameter("ConfirmPassword", param3));
try
{
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception Ex)
{
throw Ex;
}
}
public DataTable getUser(string email, string password)
{
String cs = ConfigurationManager.ConnectionStrings["WebApiEmp"].ConnectionString;
DataTable dt = new DataTable();
string commad="select * from [User] where Email='"+email+"' and Password='"+password+"'";
using (SqlConnection conn = new SqlConnection(cs))
{
using(SqlCommand cmd= new SqlCommand(commad,conn))
{
conn.Open();
try
{
SqlDataAdapter ap = new SqlDataAdapter(cmd);
ap.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
}
}
return dt;
}
}
}
The Business Layer class which interacts with the Repository class and provides data to the
Controller , All our business logics are embedded in this class
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using WebApiDemo.Models;
namespace WebApiDemo
{
public class BusinessLayer
{
public RepositoryLayer RL;
public BusinessLayer()
{
RL = new RepositoryLayer();
}
public IEnumerable<Employee> getEmployees()
{
DataTable dt=RL.getEmployee();
IEnumerable<Employee> employeeList=dt.AsEnumerable().Select(x => new Employee
{
Id = Convert.ToInt32(x["Id"]),
firstName = Convert.ToString(x["First_Name"]),
lastname = Convert.ToString(x["Last_Name"]),
gender = Convert.ToString(x["Gender"]),
salary = Convert.ToInt32(x["Salary"])
});
return employeeList;
}
public string postEmployee(Employee emp)
{
int Id=emp.Id;
string firstNam=emp.firstName;
string lastName= emp.lastname;
string gender= emp.gender;
int salary=emp.salary;
return RL.postEmployee(Id, firstNam, lastName, gender, salary);
}
public void deleteEmployee(int Id)
{
RL.deleteEmployee(Id);
}
public void UpdateEmployee(int Id, Employee emp)
{
string firstName = emp.firstName;
string lastName = emp.lastname;
string gender = emp.gender;
RL.UpdateEmployee(Id, firstName, lastName, gender);
}
public void RegisterUser(RegisterModel regmodel)
{
RL.registerEmployee(regmodel.email, regmodel.password, regmodel.confirmPassword);
}
public IEnumerable<RegisterModel> FindUser(string email, string password)
{
DataTable dt=RL.getUser(email, password);
IEnumerable<RegisterModel> user =dt.AsEnumerable().Select(row => new RegisterModel
{
email=Convert.ToString(row["Email"]),
password=Convert.ToString(row["Password"]),
confirmPassword=Convert.ToString(row["ConfirmPassword"])
});
return user;
}
}
}
The Model - Employee Class
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using WebApiDemo.Models;
namespace WebApiDemo
{
public class BusinessLayer
{
public RepositoryLayer RL;
public BusinessLayer()
{
RL = new RepositoryLayer();
}
public IEnumerable<Employee> getEmployees()
{
DataTable dt=RL.getEmployee();
IEnumerable<Employee> employeeList=dt.AsEnumerable().Select(x => new Employee
{
Id = Convert.ToInt32(x["Id"]),
firstName = Convert.ToString(x["First_Name"]),
lastname = Convert.ToString(x["Last_Name"]),
gender = Convert.ToString(x["Gender"]),
salary = Convert.ToInt32(x["Salary"])
});
return employeeList;
}
public string postEmployee(Employee emp)
{
int Id=emp.Id;
string firstNam=emp.firstName;
string lastName= emp.lastname;
string gender= emp.gender;
int salary=emp.salary;
return RL.postEmployee(Id, firstNam, lastName, gender, salary);
}
public void deleteEmployee(int Id)
{
RL.deleteEmployee(Id);
}
public void UpdateEmployee(int Id, Employee emp)
{
string firstName = emp.firstName;
string lastName = emp.lastname;
string gender = emp.gender;
RL.UpdateEmployee(Id, firstName, lastName, gender);
}
public void RegisterUser(RegisterModel regmodel)
{
RL.registerEmployee(regmodel.email, regmodel.password, regmodel.confirmPassword);
}
public IEnumerable<RegisterModel> FindUser(string email, string password)
{
DataTable dt=RL.getUser(email, password);
IEnumerable<RegisterModel> user =dt.AsEnumerable().Select(row => new RegisterModel
{
email=Convert.ToString(row["Email"]),
password=Convert.ToString(row["Password"]),
confirmPassword=Convert.ToString(row["ConfirmPassword"])
});
return user;
}
}
}
The Register Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApiDemo.Models
{
public class RegisterModel
{
public string email { get; set; }
public string password { get; set; }
public string confirmPassword { get; set; }
}
}
The DataBase Tables
SimpleAuthorizationServerProvider class which checks all the requests and marks either authenticated and authorised
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using WebApiDemo.Models;
namespace WebApiDemo.Provider
{
public class SimleAuthorizationServerProvider:OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
BusinessLayer bl = new BusinessLayer();
var R1 = bl.FindUser(context.UserName, context.Password);
if (R1 == null)
{
context.SetError("Invalid User");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
}
We have to create a startup.cs class which will be used to validate any incoming request
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using WebApiDemo.Provider;
[assembly:OwinStartup(typeof(WebApiDemo.Startup))]
namespace WebApiDemo
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
//app.UserCors(Microsoft.Owin.Cors.CorsOption.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
A Registration.htmls page is created to register new users
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top:20px">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<table class="table table-bordered">
<thead>
<tr class="success">
<td colspan="2">
New User Registration
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Email</td>
<td>
<input type="text" id="txtEmail" placeholder="Email"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="txtPassword" placeholder="Password" />
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input type="password" id ="txtPasswordConfirm" placeholder="ConfirmPassword" />
</td>
</tr>
<tr class="success">
<td colspan="2">
<input id="btnRegister" class="btn btn-success" type="button" value="Register"/>
</td>
</tr>
</tbody>
</table>
<div class="modal fade" tabindex="-1" id="successModel" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Success</h4>
</div>
<div class="modal-body">
<h2> Registration Successful</h2>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-success" type="button">Close</button>
</div>
</div>
</div>
</div>
<div class="alert alert-danger collapse" >
<a id="linkClose" class="close" href="#">×</a>
<div id="divErrorTest" ></div>
</div>
</div>
</div>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#linkClose').click(function () {
$('#divErrorTest').hide('fade');
});
$('#btnRegister').click(function () {
$ajax({
url: 'api/Employee/Register',
method : 'POST',
data : {
email : $('#txtEmail').val(),
password : $('#txtPassword').val(),
confirmPassword : $('#txtPasswordConfirm').val()
},
success:function(){
$('#successModel').modal('show');
},
error:function(jqXHR){
$('#divErrorTest').text(jqXHR.responseText);
$('#divError').show('fade');
}
}
}
$('#successModel').modal('show');
});
});
</script>
</body>
</html>
WebConfig File -
<?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=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApiDemo-20170329105301;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApiDemo-20170329105301.mdf" />
<add name="WebApiEmp" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=H:\FIRSTWEBAPISERVICE\FIRSTWEBAPISERVICE\APP_DATA\1-CLICKPUBLISH.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False"></add>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<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="None" />
<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.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<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>
</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-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.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>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
List of references and packages or dll required
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="bootstrap" version="3.3.7" targetFramework="net45" />
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="jQuery" version="1.9.1" targetFramework="net45" />
<package id="jQuery.UI.Combined" version="1.8.20.1" targetFramework="net45" />
<package id="jQuery.Validation" version="1.9.0.1" targetFramework="net45" />
<package id="knockoutjs" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Core" version="2.0.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.0.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Providers.Core" version="1.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Providers.LocalDB" version="1.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Ajax" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Modernizr" version="2.5.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="WebGrease" version="1.1.0" targetFramework="net45" />
</packages>
Comments
Post a Comment