主頁 > .NET開發 > 10分鐘簡單學習net core集成jwt權限認證,快速接入專案落地使用

10分鐘簡單學習net core集成jwt權限認證,快速接入專案落地使用

2021-11-12 06:05:59 .NET開發

什么是JWT

JSON Web Token(JWT)是目前最流行的跨域身份驗證、分布式登錄、單點登錄等解決方案,

JWT的官網地址:https://jwt.io/

通俗地來講,JWT是能代表用戶身份的令牌,可以使用JWT令牌在api介面中校驗用戶的身份以確認用戶是否有訪問api的權限,

JWT中包含了身份認證必須的引數以及用戶自定義的引數,JWT可以使用秘密(使用HMAC演算法)或使用RSA或ECDSA的公鑰/私鑰對進行簽名,

JSON Web令牌能做什么?

  1. 授權:這是使用JWT的最常見方案,一旦用戶登錄,每個后續請求將包括JWT,允許用戶訪問該令牌允許的路由,服務和資源,Single Sign On是一種現在廣泛使用JWT的功能,因為它的開銷很小,并且能夠在不同的域中輕松使用,
  2. 資訊交換:JSON Web令牌是在各方之間安全傳輸資訊的好方法,因為JWT可以簽名 - 例如,使用公鑰/私鑰對 - 您可以確定發件人是他們所說的人,此外,由于使用標頭和有效負載計算簽名,您還可以驗證內容是否未被篡改,

JSON Web令牌如何作業?

在身份驗證中,當用戶使用其憑據成功登錄時,將回傳JSON Web令牌,由于令牌是憑證,因此必須非常小心以防止出現安全問題,一般情況下,您不應該將令牌保留的時間超過要求,

每當用戶想要訪問受保護的路由或資源時,用戶代理應該使用承載模式發送JWT,通常在Authorization標頭中,標題的內容應如下所示:

Authorization: Bearer <token>

在某些情況下,這可以是無狀態授權機制,服務器的受保護路由將檢查Authorization標頭中的有效JWT ,如果存在,則允許用戶訪問受保護資源,如果JWT包含必要的資料,則可以減少查詢資料庫以進行某些操作的需要,盡管可能并非總是如此,

如果在標Authorization頭中發送令牌,則跨域資源共享(CORS)將不會成為問題,因為它不使用cookie,

下圖顯示了如何獲取JWT并用于訪問API或資源:

1、應用程式向授權服務器請求授權;

2、校驗用戶身份,校驗成功,回傳token;

3、應用程式使用訪問令牌訪問受保護的資源,

JWT的實作方式是將用戶資訊存盤在客戶端,服務端不進行保存,每次請求都把令牌帶上以校驗用戶登錄狀態,這樣服務就變成了無狀態的,服務器集群也很好擴展,

 

更多理論知識可以查看官網,或者查看相關網友的文章,如下推薦文章:

  • asp.net core 集成JWT(一):https://www.cnblogs.com/7tiny/archive/2019/06/13/11012035.html
  • 五分鐘帶你了解啥是JWT:https://zhuanlan.zhihu.com/p/86937325
  • C#分布式登錄——jwt:https://www.cnblogs.com/yswenli/p/13510050.html

net core 集成jwt代碼實作

新建專案

首先我們新建一個ASP.NET Core Web API專案,命名為 jwtWebAPI,選擇目標框架.NET Core3.1,注意,如果勾選了https配置,postman請求的時候要設定去除ssl認證才能使用,建議不配置https,

在nuget里面參考jwt集成的程式包,這里需要注意的是,如果你用的是.NET Core 3.1的框架的話,程式包版本選擇3.1.10

Microsoft.AspNetCore.Authentication.JwtBearer

 

添加資料訪問模擬api,新建控制器ValuesController

其中api/value1是可以直接訪問的,api/value2添加了權限校驗特性標簽 [Authorize]

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace jwtWebAPI.Controllers
{
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        [Route("api/values1")]
        public ActionResult<IEnumerable<string>> values1()
        {
            return new string[] { "value1", "value1" };
        }

        /**
         * 該介面用Authorize特性做了權限校驗,如果沒有通過權限校驗,則http回傳狀態碼為401
         * 呼叫該介面的正確姿勢是:
         * 1.登陸,呼叫api/Auth介面獲取到token
         * 2.呼叫該介面 api/value2 在請求的Header中添加引數 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOiIxNTYwMzM1MzM3IiwiZXhwIjoxNTYwMzM3MTM3LCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiemhhbmdzYW4iLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUwMDAifQ.1S-40SrA4po2l4lB_QdzON_G5ZNT4P_6U25xhTcl7hI
         * Bearer后面有空格,且后面是第一步中介面回傳的token值
         * */
        [HttpGet]
        [Route("api/value2")]
        [Authorize]
        public ActionResult<IEnumerable<string>> value2()
        {
            //這是獲取自定義引數的方法
            var auth = HttpContext.AuthenticateAsync().Result.Principal.Claims;
            var userName = auth.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
            return new string[] { "訪問成功:這個介面登陸過的用戶都可以訪問", $"userName={userName}" };
        }

     
    }
}

添加模擬登陸生成Token的api,新建控制器AuthController

這里模擬一下登陸校驗,只驗證了用戶密碼不為空即通過校驗,真實環境完善校驗用戶和密碼的邏輯,

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace jwtWebAPI.Controllers
{
    [ApiController]
    public class AuthController : Controller
    {
        /// <summary>
        /// 通過賬號+密碼獲取Token
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns>Token</returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("api/auth")]
        public IActionResult GetToken(string userName, string pwd)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                //每次登陸動態重繪
                Const.ValidAudience = userName + pwd + DateTime.Now.ToString();
                // push the user’s name into a claim, so we can identify the user later on.
                //這里可以隨意加入自定義的引數,key可以自己隨便起
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(3)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.NameIdentifier, userName)
                };
                //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
                var token = new JwtSecurityToken(
                    //頒發者
                    issuer: Const.Domain,
                    //接收者
                    audience: Const.ValidAudience,
                    //過期時間(可自行設定,注意和上面的claims內部Exp引數保持一致)
                    expires: DateTime.Now.AddMinutes(3),
                    //簽名證書
                    signingCredentials: creds,
                    //自定義引數
                    claims: claims
                    );

                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }
            else
            {
                return BadRequest(new { message = "username or password is incorrect." });
            }
        }
    }
}

Startup添加JWT驗證的相關配置

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jwtWebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //添加jwt驗證:
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateLifetime = true,//是否驗證失效時間
                        ClockSkew = TimeSpan.FromSeconds(30),  //時間偏移量(允許誤差時間)
                        ValidateAudience = true,//是否驗證Audience(驗證之前的token是否失效)
                        //ValidAudience = Const.GetValidudience(),//Audience
                        //這里采用動態驗證的方式,在重新登陸時,重繪token,舊token就強制失效了
                        AudienceValidator = (m, n, z) =>
                        {
                            return m != null && m.FirstOrDefault().Equals(Const.ValidAudience);
                        },
                        ValidateIssuer = true,//是否驗證Issuer(頒發者)
                        ValidAudience = Const.Domain,//Audience    【Const是新建的一個常量類】  接收者 
                        ValidIssuer = Const.Domain,//Issuer,這兩項和前面簽發jwt的設定一致      頒發者
                        ValidateIssuerSigningKey = true,//是否驗證SecurityKey
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到秘鑰SecurityKey
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            //Token expired
                            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                            {
                                context.Response.Headers.Add("Token-Expired", "true");
                            }
                            return Task.CompletedTask;
                        }
                    };
                });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        { 
            //添加jwt驗證
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

創建常量類Const

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace jwtWebAPI
{
    public class Const
    {
        /// <summary>
        /// 這里為了演示,寫死一個密鑰,實際生產環境可以從組態檔讀取,這個是用網上工具隨便生成的一個密鑰(md5或者其他都可以)
        /// </summary>
        public const string SecurityKey = "48754F4C58F9EA428FE09D714E468211";

        /// <summary>
        /// 站點地址(頒發者、接受者),這里測驗和當前本地運行網站相同,實際發到正式環境應為域名地址
        /// </summary>
        public const string Domain = "https://localhost:44345";

        /// <summary>
        /// 受理人,之所以弄成可變的是為了用介面動態更改這個值以模擬強制Token失效
        /// 真實業務場景可以在資料庫或者redis存一個和用戶id相關的值,生成token和驗證token的時候獲取到持久化的值去校驗
        /// 如果重新登陸,則重繪這個值
        /// </summary>
        public static string ValidAudience;
    }
}

JWT登錄授權測驗成功

把程式編譯運行起來,打開postman,輸入地址,首先測驗不需要任何授權的

 

 

正確地回傳了資料,那么接下來我們測驗JWT的流程,

首先我們什么都不加呼叫介面:https://localhost:44345/api/values2,注意,我創建的時候是https的,大家注意看是http還是https

 

回傳了狀態碼401,也就是未經授權:訪問由于憑據無效被拒絕, 說明JWT校驗生效了,我們的介面收到了保護,

呼叫模擬登陸授權介面:https://localhost:44345/api/auth?userName=xiongze&pwd=123456

這里的用戶密碼是隨便寫的,因為我們模擬登陸只是校驗了下非空,因此寫什么都能通過,

 

然后我們得到了一個xxx.yyy.zzz 格式的 token 值,我們把token復制出來,

在剛才401的介面(https://localhost:44345/api/values2)請求header中添加JWT的引數,把我們的token加上去

再次呼叫我們的模擬資料介面,但是這次我們加了一個header,KEY:Authorization     Value:Bearer Tokne的值

這里需要注意 Bearer 后面是有一個空格的,然后就是我們上一步獲取到的token,

 

得到回傳值,正確授權成功,我們是支持自定義回傳引數的,上面代碼里面有相關內容,比如用戶名這些不敏感的資訊可以帶著回傳,

等token設定的過期時間到了,或者重新生成了新的Token,沒有及時更新,那么我們的授權也到期,401,

升級操作:介面權限隔離

上面的操作是所有登錄授權成功的角色都可以進行呼叫所有介面,那么我們現在想要進行介面隔離限制,

也就是說,雖然授權登錄了,但是我這個介面是指定權限訪問的,

比如說:洗掉介面只能管理員角色操作,那么其他角色雖然授權登錄了,但是沒有權限呼叫洗掉介面,

我們在原來的操作進行改造升級看一下,

添加類

新建一個AuthManagement檔案夾,添加PolicyRequirement類PolicyHandler類

PolicyRequirement類:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace jwtWebAPI.AuthManagement
{
    /// <summary>
    /// 權限承載物體
    /// </summary>
    public class PolicyRequirement : IAuthorizationRequirement
    {
        /// <summary>
        /// 用戶權限集合
        /// </summary>
        public List<UserPermission> UserPermissions { get; private set; }
        /// <summary>
        /// 無權限action
        /// </summary>
        public string DeniedAction { get; set; }
        /// <summary>
        /// 構造
        /// </summary>
        public PolicyRequirement()
        {
            //沒有權限則跳轉到這個路由
            DeniedAction = new PathString("/api/nopermission");
            //用戶有權限訪問的路由配置,當然可以從資料庫獲取
            UserPermissions = new List<UserPermission> {
                              new UserPermission {  Url="/api/values3", UserName="admin"},
                          };
        }
    }

    /// <summary>
    /// 用戶權限承載物體
    /// </summary>
    public class UserPermission
    {
        /// <summary>
        /// 用戶名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 請求Url
        /// </summary>
        public string Url { get; set; }
    }
}

PolicyHandler類(注意2.x和3.x的區別)

 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace jwtWebAPI.AuthManagement
{
    public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public PolicyHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            //賦值用戶權限
            var userPermissions = requirement.UserPermissions;
            var httpContext = _httpContextAccessor.HttpContext;

            //請求Url
            var questUrl = httpContext.Request.Path.Value.ToUpperInvariant();
            //是否經過驗證
            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
            if (isAuthenticated)
            {
                if (userPermissions.GroupBy(g => g.Url).Any(w => w.Key.ToUpperInvariant() == questUrl))
                {
                    //用戶名
                    var userName = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.NameIdentifier).Value;
                    if (userPermissions.Any(w => w.UserName == userName && w.Url.ToUpperInvariant() == questUrl))
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        ////無權限跳轉到拒絕頁面
                        //httpContext.Response.Redirect(requirement.DeniedAction);
                        return Task.CompletedTask;
                    }
                }
                else
                {
                    context.Succeed(requirement);
                }
            }
            return Task.CompletedTask;
        }
    }
}

添加指定角色

在 AuthController 控制器的GetToken授權加入自定義的引數,如下

new Claim("Role", userName)  //這里是角色,我使用登錄賬號admin代替

 

在 AuthController 控制器里面添加無權限訪問的方法

[AllowAnonymous]
[HttpGet]
[Route("api/nopermission")]
public IActionResult NoPermission()
{
     return Forbid("No Permission!");
}

 

修改Startup配置

在startup.cs的ConfigureServices 方法里面添加策略鑒權模式、添加JWT Scheme、注入授權Handler 

修改后的檔案如下

using jwtWebAPI.AuthManagement;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jwtWebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
                //添加策略鑒權模式
                .AddAuthorization(options =>
                {
                    options.AddPolicy("Permission", policy => policy.Requirements.Add(new PolicyRequirement()));
                })
                //添加JWT Scheme
                .AddAuthentication(s =>
                {
                    s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    s.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                //添加jwt驗證:
                .AddJwtBearer(options => {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateLifetime = true,//是否驗證失效時間
                        ClockSkew = TimeSpan.FromSeconds(30),  //時間偏移量(允許誤差時間)
                        ValidateAudience = true,//是否驗證Audience(驗證之前的token是否失效)
                        //ValidAudience = Const.GetValidudience(),//Audience
                        //這里采用動態驗證的方式,在重新登陸時,重繪token,舊token就強制失效了
                        AudienceValidator = (m, n, z) =>
                        {
                            return m != null && m.FirstOrDefault().Equals(Const.ValidAudience);
                        },
                        ValidateIssuer = true,//是否驗證Issuer(頒發者)
                        ValidAudience = Const.Domain,//Audience    【Const是新建的一個常量類】  接收者 
                        ValidIssuer = Const.Domain,//Issuer,這兩項和前面簽發jwt的設定一致      頒發者
                        ValidateIssuerSigningKey = true,//是否驗證SecurityKey
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到秘鑰SecurityKey
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            //Token expired
                            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                            {
                                context.Response.Headers.Add("Token-Expired", "true");
                            }
                            return Task.CompletedTask;
                        }
                    };
                });

            //注入授權Handler
            services.AddSingleton<IAuthorizationHandler, PolicyHandler>();
            //注入獲取HttpContext
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        { 
            //添加jwt驗證
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            
        }
    }
}

 

添加api訪問的方法

在 ValuesController控制器添加指定權限訪問的方法,如下:

        /**
        * 這個介面必須用admin
        **/
        [HttpGet]
        [Route("api/values3")]
        [Authorize("Permission")]
        public ActionResult<IEnumerable<string>> values3()
        {
            //這是獲取自定義引數的方法
            var auth = HttpContext.AuthenticateAsync().Result.Principal.Claims;
            var userName = auth.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
            var role = auth.FirstOrDefault(t => t.Type.Equals("Role"))?.Value;

            return new string[] { "訪問成功:這個介面有管理員權限才可以訪問", $"userName={userName}", $"Role={role}" };
        }

不同權限測驗訪問

我們同樣的方法去模擬登錄,https://localhost:44345/api/auth?userName=xiongze&pwd=123

注意,賬號先不用admin登錄,然后用回傳的token去請求我們剛剛添加的指定權限訪問的介面,這個時候是沒有權限訪問的,因為這個是admin權限訪問,

我們同樣的方法去模擬登錄,https://localhost:44345/api/auth?userName=admin&pwd=123

訪問成功,

原始碼下載地址

Gitee:https://gitee.com/xiongze/jwtWebAPI.git

參考文獻

  • asp.net core 集成JWT(一):https://www.cnblogs.com/7tiny/archive/2019/06/13/11012035.html
  • 五分鐘帶你了解啥是JWT:https://zhuanlan.zhihu.com/p/86937325
  • C#分布式登錄——jwt:https://www.cnblogs.com/yswenli/p/13510050.html

 

  歡迎關注訂閱微信公眾號【熊澤有話說】,更多好玩易學知識等你來取
作者:熊澤-學習中的苦與樂
公眾號:熊澤有話說
出處: https://www.cnblogs.com/xiongze520/p/15540035.html
您可以隨意轉載、摘錄,但請在文章內注明作者和原文鏈接,  

 

 

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355991.html

標籤:.NET Core

上一篇:CentOS8.0安裝Nacos

下一篇:事件訊息生產消費中間件-OSS.DataFlow

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more