[英]Handle asmx C# Exception with fetch API
首先,對不起我的英語...
我在C#中有一個asmx,它在客戶端使用fetch API調用在json中發送數據,我以前使用過jQuery.Ajax
調用,但是我想開始使用fetch API。
這就是我進行提取呼叫的方式。
我通過傳遞URL來調用函數fetchcall,如果需要的話,JS對象以及要通過POST
發送的參數
const jdata = await fetchcall(url, "")
然后在我的職能中我這樣做
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json'
//credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
const response = await fetch(url, PostData)
const json = await (handleErrors(response)).json();
//This is a temporary solution to the problem
if (json == 'Su sesion ha expirado favor de ir a pagina de login e iniciar session') {
alert(json);
return false;
}
return json
} catch (e) {
console.log(e)
}}
這是handleErrors
函數
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
現在我正在測試錯誤而不發送憑據,所以我在Session
遇到了錯誤
在我的C#asmx中,我有這個
[WebMethod(Description = "Load Countries", EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string fillcbocountries()
{
var authCookie = Session["uid"];
if (authCookie == null)
throw new Exception("Your session has expired please go to login page and start session");}
Web服務向我拋出錯誤,提示您您的會話已過期,請轉到登錄頁面並開始會話
但是,當我在handleError函數中檢查提取API的響應時,我只得到一個statusText:"Internal Server Error"
並且我希望服務器響應的消息。
使用jQuery.Ajax我做到了
error: function (xhr, textStatus, error) {
var errorM = $.parseJSON(xhr.responseText);
console.log(errorM.Message)
}
我得到了
您的會話已過期,請轉到登錄頁面並開始會話
謝謝您的幫助和問候
我發現如果從C#發送異常,如何正確處理錯誤
我刪除了handleErrors
功能,檢查里面的響應fetchcall
所以如果response.ok
是false
,然后我檢查JSON數據的服務器響應,並獲得json.Message
。
這是結束碼
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json',
credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
//const url = 'services/common.asmx/fillcbopais'
const response = await fetch(url, PostData)
const jdata = await response.json();
if (!response.ok) {
alert(jdata.Message);
throw Error(jdata.Message)
}
return json
} catch (e) {
console.log(e)
}}
萬一別人有這個問題,我希望我能幫忙
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.