C# 如何将错误返回到ajax请求

C# 如何将错误返回到ajax请求,c#,jquery,asp.net,ajax,C#,Jquery,Asp.net,Ajax,我有一个从ajax调用的WebMethod——如果抛出错误,如果类型不是string/int等,如何将其返回到ajax请求 [WebMethod] public static List<SchedulerResource> getResourcesOnCall(Guid instructionID, bool ignorePostcode, int pageIndex, int pageSize) { int totalRows = 0; List<Schedu

我有一个从ajax调用的WebMethod——如果抛出错误,如果类型不是string/int等,如何将其返回到ajax请求

[WebMethod]
public static List<SchedulerResource> getResourcesOnCall(Guid instructionID, bool ignorePostcode, int pageIndex, int pageSize)
{
    int totalRows = 0;
    List<SchedulerResource> schedulerResourceDS = null;

    try
    { 
        schedulerResourceDS = NewJobBLL.GetResourcesOnCall(instructionID, ignorePostcode, pageIndex, pageSize, ref totalRows);

        return schedulerResourceDS;
    }
    catch (Exception ex)
    {
        // what do I send back here?
    }

    return schedulerResourceDS;
}
编辑:我不认为它是重复的-我在问如果它的类型是List,如何从我的WebMethod返回statusCode(int)或statusText(string)。因此,我得到以下错误:

无法将类型“System.Net.HttpStatusCode”隐式转换为“System.Collections.Generic.List”


您可以使方法返回
对象
而不是
列表
或者尝试将JSON字符串返回给客户端。这样,您就可以灵活地选择返回的内容

我们可以找到一个很好的例子

对于将对象序列化为JSON,可以使用

我不使用ASP.NET,但在ASP.NET MVC中,这看起来像这样: 您可以使方法返回
JsonResult
而不是
List

然后,如果发生错误,您可以返回

Response.StatusCode = 500;
return Json(new {error = ex.Message}, JsonRequestBehavior.AllowGet);
catch (WebException ex)
{
    var statusCode = ((HttpWebResponse)ex.Response).StatusCode;

    return statusCode;
}
return Json(schedulerResourceDS, JsonRequestBehavior.AllowGet);
Response.StatusCode = 500;
return Json(new {error = ex.Message}, JsonRequestBehavior.AllowGet);