内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

asp.netcore跨域訪問ajax的驗證訪問

跨域需要服務(wù)端和客戶端都作處理。

創(chuàng)新互聯(lián)專注于祥符網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供祥符營銷型網(wǎng)站建設(shè),祥符網(wǎng)站制作、祥符網(wǎng)頁設(shè)計、祥符網(wǎng)站官網(wǎng)定制、微信平臺小程序開發(fā)服務(wù),打造祥符網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供祥符網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

首先讓asp.net core跨域,在nuget中添加Microsoft.AspNetCore.Cors的引用,然后在StartUp.cs中的ConfigureServices中添加如下代碼:

    var urls = "http://localhost:5000/";
    services.AddCors(options =>
    options.AddPolicy("MyDomain",
builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

再在Configure中添加

app.UseCors("AllowSameDomain");
再添加驗證,添加Microsoft.AspNetCore.Authentication.Cookies引用
在Configure中添加
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "validates",
    LoginPath = new Microsoft.AspNetCore.Http.PathString("/login"),
    AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Home/Error"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    SlidingExpiration = true
});

在Controller中添加允許跨域特性,然后再添驗證特性

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
 
namespace WebUI.Controllers
{
    [Authorize(Roles = "Admin")]
    [EnableCors("MyDomain")]
    public class HomeController : Controller
    {
        /// <summary>
        /// 測試方法
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost("additem")]
        public IActionResult AddItem(Item item)
        {
            return new JsonResult(new { Result = 0, Message = "添加成功", Content = item.ToString(), UserName = User.Identity.Name }, new Newtonsoft.Json.JsonSerializerSettings());
        }
        /// <summary>
        /// 登錄
        /// </summary>
        /// <param name="username">用戶名</param>
        /// <param name="password">密碼</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("login")]
        public IActionResult Login(string username, string password)
        {
            if (username == "aaa" && password == "111")
            {
 
                var user = new { RoleType = 1, Name = "張三豐", ID = 1 };
                string roleId = user.RoleType.ToString();
                var roleName = "";
                switch (roleId)
                {
                    case "1":
                        roleName = "Admin";//管理員
                        break;
                }
                var id = user.ID.ToString();
                var claims = new Claim[] {
                      new Claim(ClaimTypes.UserData,roleId),
                      new Claim(ClaimTypes.Role,roleName),
                      new Claim(ClaimTypes.Name,username)
                };
                HttpContext.Authentication.SignInAsync("validates", new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie")));
                HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
 
                return new JsonResult(new { Message = "登錄成功" }, new Newtonsoft.Json.JsonSerializerSettings());
 
            }
            else
            {
 
                return new JsonResult(new { Message = "用戶名或密碼錯誤" }, new Newtonsoft.Json.JsonSerializerSettings());
            }
        }
    }
}
在JQuery中,使用$.ajax登錄后,才能執(zhí)行保存,否則沒有權(quán)限保存數(shù)據(jù),重點時ajax請求時xhrFields: {withCredentials: true }這個屬性,可以把登錄后的cookie在后面的操作中帶回服務(wù)端(關(guān)于原理不多說了)
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <script src="bower_components/jquery/dist/jquery.js"></script>
</head>
<body>
    <input id="login" value="登錄" type="button" />
    <input id="sava" value="保存" type="button" />
    <span id="message"></span>
    <script>
        $("#login").click(function () {
            $.ajax({
                type: 'POST',
                url: "http://localhost:5000/login",
                data: { username: "aaa", password: "111" },
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                success: function (result) {
                    $("#message").html(result.Message);
                },
                error: function () {
                    $("#message").html("登錄失敗!");
                }
            });
        })
 
        $("#sava").click(function () {
            $.ajax({
                type: 'POST',
                url: "http://localhost:5000/additem",
                data: { ID: 112, Name: "李四", Birthday: "2017-01-23" },
                dataType: "json",
                //必須有這項的配置,不然cookie無法發(fā)送至服務(wù)端
                xhrFields: {
                    withCredentials: true
                },
                success: function (result) {
                    $("#message").html(result.Message + result.Content + result.UserName);
                },
                error: function (xhr,status) {
                    $("#message").html(status);
                }
            });
        })
    </script>
</body>
</html>

來看一下測試結(jié)果:

當(dāng)直接點保存時,系統(tǒng)會導(dǎo)航登錄

asp.net core跨域訪問ajax的驗證訪問

登錄

asp.net core跨域訪問ajax的驗證訪問

再次保存

asp.net core跨域訪問ajax的驗證訪問

分享名稱:asp.netcore跨域訪問ajax的驗證訪問
網(wǎng)頁URL:http://www.rwnh.cn/article8/jgjgop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、微信小程序自適應(yīng)網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)、微信公眾號、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)
毕节市| 清水河县| 老河口市| 房产| 徐水县| 无为县| 乐平市| 海伦市| 辛集市| 横峰县| 九江市| 无为县| 吐鲁番市| 武穴市| 陆丰市| 齐河县| 呼和浩特市| 岳普湖县| 武冈市| 乳源| 和顺县| 石棉县| 遂平县| 油尖旺区| 古田县| 永嘉县| 友谊县| 广安市| 将乐县| 濮阳县| 海晏县| 宁明县| 镇远县| 自治县| 贡山| 荥经县| 鹤岗市| 麻城市| 建德市| 天峻县| 红安县|