[英]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.