前面我们从后台访问Web Api,现在我们使用jQuery来实现访问。创建一个新的页面,在OnGet中获取access_token并保存:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json.Linq;
namespace MyClientWebHttps.Pages
{
public class GetDataJsModel : PageModel
{
public string token;
public async Task OnGet()
{
var auth = await HttpContext.AuthenticateAsync();
var tokens = auth.Properties;
token = tokens.Items[".Token.access_token"];
}
}
}
在页面上编写jQuery调用Web Api的代码:
@page
@model MyClientWebHttps.Pages.GetDataJsModel
@{
}
<div>
@Model.result
</div>
<div id="result">
</div>
@section Scripts
{
<script type="text/javascript">
var token = "@Model.token";
var UserApiUrl = "http://localhost:5007/WeatherForecast";
$(document).ready(function () {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
},
url: UserApiUrl,
type: 'get',
success: function (res) {
$("#result").text(res);
alert("success");
},
error: function (err) {
console.log(err);
alert(err.statusText);
}
});
});
</script>
}
与一般调用时的区别是增加了beforeSend,里面增加认证。访问时会发生错误,不允许跨域访问,还需要在Web Api中增加CORS的设置:
services.AddCors(option => option.AddPolicy("cors",
policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins(new[] { "https://localhost:5006" })));
......
app.UseCors("cors");
这样就可以了。
网友评论