2021年12月17日 星期五

asp.net mvc api 學習心得

網址指定action name 呼叫對應action
WebApiConfig.cs routeTemplate 加入 {action}
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}", 
defaults: new { id = RouteParameter.Optional }
);

Authorize 導入JWT
●安裝 jwt.net
●新增 JwtAuthorizeAttribute class
using System.Net.Http; // to use GetRequestContext()
public class JwtAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var authorization = actionContext.Request.Headers.Authorization;
if (authorization != null && authorization.Scheme == "Bearer")
{
var token = authorization.Parameter;
var secret = System.Web.Configuration.WebConfigurationManager.AppSettings["JWTSecret"];
var claims = JwtBuilder.Create()
.WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
.WithSecret(secret)
.MustVerifySignature()
.Decode<IDictionary<string, object>>(token).Select(a => new Claim(a.Key.ToLower() == "name" ? ClaimTypes.Name : a.Key.ToLower() == "role" ? ClaimTypes.Role : a.Key, a.Value.ToString()) { });
var identity = new ClaimsIdentity(claims, "JWT");
var principal = new ClaimsPrincipal(identity);
actionContext.Request.GetRequestContext().Principal = principal;
}
return base.IsAuthorized(actionContext);
}
}
●webapiconfig.cs 加入
config.Filters.Add(new JwtAuthorizeAttribute());

被呼叫端Controller
public class p
{
    public string lineid { get; set; }
}
[JwtAuthorize]
public class xxxController : ApiController
{
[HttpPost]
public IHttpActionResult aaa([FromBody] p p1)
{
                try {
...
return Ok(xxx);
                }
                catch (Exception ex)
                {
                    return BadRequest(ex.Message);
                }

產生token
var secret = System.Web.Configuration.WebConfigurationManager.AppSettings["JWTSecret"];
var token = JWT.Builder.JwtBuilder.Create()
  .WithAlgorithm(new JWT.Algorithms.HMACSHA256Algorithm()) // symmetric
  .WithSecret(secret)
  .AddClaim("exp", DateTimeOffset.UtcNow.AddMinutes(1).ToUnixTimeSeconds())
                  .AddClaim("role", 123)
  .Encode();

呼叫端
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var stringContent = new StringContent(JsonConvert.SerializeObject(new { lineid = "12345" }), System.Text.Encoding.UTF8, "application/json");
using (var response = await httpClient.PostAsync("...", stringContent))
{
string responseBody = await response.Content.ReadAsStringAsync();
                if (response.StatusCode == HttpStatusCode.OK)
var jobj = JsonConvert.DeserializeObject<JObject>(responseBody);
}
}

沒有留言:

input 連結 datalist 用程式控制彈出選項

範例: nextTick(() => document.querySelector('input').showPicker());  ※僅支援現代瀏覽器