public class ValuesController : ApiController
{
// GET: api/Values
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
public class CustomersController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> GetCustomer(int id)
{
Customer customer = await db.Customers.FindAsync(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
// PUT: api/Customers/5
[Authorize]
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCustomer(int id, Customer customer)
{
// ...
}
// POST: api/Customers
[Authorize]
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> PostCustomer(Customer customer)
{
// ...
}
// DELETE: api/Customers/5
[ResponseType(typeof(Customer))]
[Authorize]
public async Task<IHttpActionResult> DeleteCustomer(int id)
{
// ...
}
}
var formatters = GlobalConfiguration.Configuration.Formatters; var jsonFormatter = formatters.JsonFormatter; var settings = jsonFormatter.SerializerSettings; settings.Formatting = Formatting.Indented; settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Install-Package Microsoft.AspNet.WebApi.Cors
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// ...
}
}
public class ApplicationUser : IdentityUser
{
// ...
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// ...
}
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// ..
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// ..
}
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// ...
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new []{"*"});
// ...
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// ...
return manager;
}
<div id="app">
<div class="container">
<span id="message">{{ msg }}</span>
</div>
<div class="container">
<div class="form-group">
<label>电子邮箱</label>
<input type="text" v-model="registerModel.email" />
</div>
<div class="form-group">
<label>密码</label>
<input type="text" v-model="registerModel.password" />
</div>
<div class="form-group">
<label>确认密码</label>
<input type="text" v-model="registerModel.confirmPassword" />
</div>
<div class="form-group">
<label></label>
<button @click="register">注册</button>
</div>
</div>
</div>
var demo = new Vue({
el: '#app',
data: {
registerUrl: 'http://localhost:10648/api/Account/Register',
registerModel: {
email: '',
password: '',
confirmPassword: ''
},
msg: ''
},
methods: {
register: function() {
var vm = this
vm.msg = ''
$.ajax({
url: vm.registerUrl,
type: 'POST',
dataType: 'json',
data: vm.registerModel,
success: function() {
vm.msg = '注册成功!'
},
error: vm.requestError
})
},
requestError: function(xhr, errorType, error) {
this.msg = xhr.responseText
}
}
})
<div id="app">
<div class="container text-center">
<span id="message">{{ msg }}</span>
</div>
<div class="container">
<div class="account-info">
<span v-if="userName">{{ userName }} | <a href="#" rel="external nofollow" @click="logout">注销</a></span>
</div>
</div>
<div class="container">
<div class="form-group">
<label>电子邮箱</label>
<input type="text" v-model="loginModel.username" />
</div>
<div class="form-group">
<label>密码</label>
<input type="text" v-model="loginModel.password" />
</div>
<div class="form-group">
<label></label>
<button @click="login">登录</button>
</div>
</div>
</div>
var demo = new Vue({
el: '#app',
data: {
loginUrl: 'http://localhost:10648/token',
logoutUrl: 'http://localhost:10648/api/Account/Logout',
loginModel: {
username: '',
password: '',
grant_type: 'password'
},
msg: '',
userName: ''
},
ready: function() {
this.userName = sessionStorage.getItem('userName')
},
methods: {
login: function() {
var vm = this
vm.msg = ''
vm.result = ''
$.ajax({
url: vm.loginUrl,
type: 'POST',
dataType: 'json',
data: vm.loginModel,
success: function(data) {
vm.msg = '登录成功!'
vm.userName = data.userName
sessionStorage.setItem('accessToken', data.access_token)
sessionStorage.setItem('userName', vm.userName)
},
error: vm.requestError
})
},
logout: function() {
var vm = this
vm.msg = ''
$.ajax({
url: vm.logoutUrl,
type: 'POST',
dataType: 'json',
success: function(data) {
vm.msg = '注销成功!'
vm.userName = ''
vm.loginModel.userName = ''
vm.loginModel.password = ''
sessionStorage.removeItem('userName')
sessionStorage.removeItem('accessToken')
},
error: vm.requestError
})
},
requestError: function(xhr, errorType, error) {
this.msg = xhr.responseText
}
}
})
<div class="container text-center">
<div>
<button @click="callApi">调用API</button>
</div>
<div class="result">
API调用结果:{{ result | json }}
</div>
</div>
callApi: function() {
var vm = this
vm.msg = ''
vm.result = ''
headers = {}
headers.Authorization = 'Bearer ' + sessionStorage.getItem('accessToken');
$.ajax({
type: 'get',
dataTye: 'json',
url: vm.apiUrl,
headers: headers,
success: function(data) {
vm.result = data
},
error: vm.requestError
})
}
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
image
register: function() {
this.$http.post(this.registerUrl, this.registerModel)
.then((response) => {
this.msg = '注册成功!'
}).catch((response) => {
this.msg = response.json()
})
}
Vue.http.options.emulateJSON = true
this.$http.post(this.registerUrl, this.registerModel ,{ emulateJSON : true})
.then( (response) => {
this.msg = '注册成功!'
})
login: function() {
this.$http.post(this.loginUrl, this.loginModel)
.then((response) => {
var body = response.json()
this.msg = '登录成功!'
this.userName = body.userName
sessionStorage.setItem('accessToken', body.access_token)
sessionStorage.setItem('userName', body.userName)
}).catch(this.requestError)
},
logout: function() {
this.$http.post(this.logoutUrl)
.then((response) => {
this.msg = '注销成功!'
this.userName = ''
this.loginModel.username = ''
this.loginModel.password = ''
sessionStorage.removeItem('userName')
sessionStorage.removeItem('accessToken')
}).catch(this.requestError)
},
requestError: function(response) {
this.msg = response.json()
}
callApi: function() {
var headers = {}
headers.Authorization = 'Bearer ' + sessionStorage.getItem('accessToken')
this.$http.get(this.apiUrl, {
headers: headers
})
.then((response) => {
this.result = response.json()
}).catch(this.requestError)
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有