在IDS4Client这个项目Views/Home目录下增加一个视图JSClient.cshtml,代码如下:
@using Microsoft.AspNetCore.Authentication
@{
var auth = await Context.AuthenticateAsync();
var token = auth.Properties.Items[".Token.access_token"];
}
<div id="result"">
</div>
@section Scripts
{
<script>
$(document).ready(function(){
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + "@token");
},
url: "http://localhost:5153/WeatherForecast",
type: 'get',
success: function (res) {
console.log(res);
for(var i=0;i<res.length;i++){
$("#result").append("<div>" +res[i].date + " : " + res[i].temperatureC + "</div>");
}
alert("success");
},
error: function (err) {
console.log(err);
alert(err.statusText);
}
});
});
</script>
}
代码很简单,直接了当。我们从当前上下文中获取Access Token,在Ajax的beforeSend中使用token进行认证,后面的访问部分没有什么特殊的。 在HomeController中增加下面的代码:
public IActionResult JSClient()
{
return View();
}
同时运行客户端和Web Api,登录后访问https://localhost:7002/Home/JSClient,看一下效果。不出意外的话,应该报错,我们会发现CORS错误,也就是从浏览器中使用Ajax直接访问Web Api受到跨域访问的限制。这需要我们对Web Api进行修改,增加对跨域访问的支持:
builder.Services.AddCors(option => option.AddPolicy("cors",
policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins(new[] { "https://localhost:7002" })));
... ...
app.UseCors("cors");
重新运行,这次可以了:
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。