前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >NetCore 简单容器实现

NetCore 简单容器实现

作者头像
冬夜先生
发布2021-12-05 18:03:30
发布2021-12-05 18:03:30
31600
代码可运行
举报
文章被收录于专栏:csicocsico
运行总次数:0
代码可运行

在IDS4Client这个项目Views/Home目录下增加一个视图JSClient.cshtml,代码如下:

代码语言:javascript
代码运行次数:0
复制
@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中增加下面的代码:

代码语言:javascript
代码运行次数:0
复制
        public IActionResult JSClient()
        {
            return View();
        }

同时运行客户端和Web Api,登录后访问https://localhost:7002/Home/JSClient,看一下效果。不出意外的话,应该报错,我们会发现CORS错误,也就是从浏览器中使用Ajax直接访问Web Api受到跨域访问的限制。这需要我们对Web Api进行修改,增加对跨域访问的支持:

代码语言:javascript
代码运行次数:0
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档