2021年8月18日 星期三

action 加入 async 造成前端無法呼叫

c#
====
public async void aaa()
{
}

javascript
====
axios.post('./aaa')
.then(response => {                               
}).catch(function (error) {
console.log(error);
})

解法:
1. void 改成 Task
2. web.config 加入
<add key="aspnet:AllowAsyncDuringSyncStages" value="true"/>
※理論上不該允許同步中包含非同步,此為寫法錯誤

javascript 透過 async 和 await 進行同步作業

async aaa() {
        let result=0;
await axios.post('./aaa')
.then(response => {
                        result=response.data;
}).catch(function (error) {
console.log(error);
});     
        consloe.log(result); // 等待 post 完成後才會執行
}

2021年8月17日 星期二

呼叫網址及驗證機制

呼叫端
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
var stringContent = new StringContent(JsonConvert.SerializeObject(new {p1=123,p2="aaa"}), System.Text.Encoding.UTF8, "application/json");
using (var response = await httpClient.PostAsync(url, stringContent)) 
{ }
}

被呼叫端
[AllowAnonymous]
[HttpPost]
public void xxx(int p1,string p2)
{
if (Request.Headers["Authorization"]!=token) {
                Response.Write("非法呼叫");
                Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                return;
        }
}

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new var newmodel = _contextXXX.CreateProxy<yyy>(); ... _contextXXX.yyy.Add(newmodel); await _contextXXX.SaveC...