已经挖了3天,仍然无法找到一个好的答案。真的很感谢,如果有人可以帮助我 例如。客户端使用登录功能从www.client.com到 我的web api验证成功并向用户发送令牌。客户如何使用令牌API返回与Web api如何使用从API发送的令牌
[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
List<customer> list = new List<customer>() { new customer {id=1 ,customerName="Marry",age=13},
new customer { id = 2, customerName = "John", age = 24 } };
[Route("GetExployeeByID/{id:long}")]
[HttpGet]
[Authorize]
public customer GetExployeeByID(long id)
{
return list.FirstOrDefault(x => x.id == id);
}
}
客户端脚本
function login() {
$.ajax({
url: 'http://www.azapi.com:81/token',
contenttype: 'application/json',
data: { username: '[email protected]', password: '[email protected]', grant_type: 'password' },
type: 'post',
crossDomain: true,
success: function (data) {
sessionStorage.setItem('token', data.access_token)
},
error: function (err) {
debugger
alert('error')
}
})
}
function getEmployee() {
$.ajax({
url: 'http://www.azapi.com:81/api/customer/GetExployeeByID/1',
datatype: "json",
type: 'get',
headers: {
"access_token": sessionStorage.getItem("token")
},
crossDomain: true,
success: function (data) {
debugger
alert(data.customerName)
},
error: function (err) {
debugger
alert('error')
}
})
}
属性的方法来访问的方法。客户端呼吁从跨域全光照阿贾克斯的方法和我的WebAPI已经在web.config中
我在方法本身拉头?意味着我的方法应该有一个头/ URL的参数?但不允许访问该方法,因为它不是授权的 –
不,您将标头置于REQUEST中。该请求应该添加标题。每当请求到达时你都要检查标题。这可以通过全局(基本)ApiController或通过FilterAttribute来实现。 – HGMamaci
如果我加入了令牌到的HttpOnly的cookie,你知道我怎么能读取和设置令牌服务器端后,我将请求发送 – DevEng