【问题标题】:How to get data from C# Webmethod via AJAX statuscode?如何通过 AJAX 状态码从 C# Webmethod 获取数据?
【发布时间】:2018-10-15 10:47:10
【问题描述】:

我正在开发一个代码来检查服务器上是否已经存在数据。如果有冲突,那么程序必须返回状态码409。我可以通过ajax.success获取webmethod返回的数据。但是,我无法通过 ajax.statusCode 获取数据。它总是返回错误:

类型错误:数据未定义

我尝试过this,但出现错误

不可调用的成员“内容”不能像方法一样使用

如何通过 ajax.statusCode 获取我的对象?

C#:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
 {
     try
     {
        Case caseResponse = new Case();

        //some process about checking if the ID exists and loading other data

        if(idCount > 0)
        {
            HttpContext.Current.Response.StatusCode = 409;
            return caseResponse;
        }
        else
        {
            HttpContext.Current.Response.StatusCode = 200; 
            return caseResponse;
        } 
     }
     catch (Exception ex)
     {
         HttpContext.Current.Response.StatusCode = 500;
         return null;
     }
}

JS:

function newCase() {

$.ajax({
    url: 'Default.aspx/CreateNewCase',
    data: JSON.stringify(
        {id: ID }
    ),
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    statusCode: {
        409: function (data, response) {
             //how do I get the "data" from WebMethod here?
             loadCase(ID, data);
             //TypeError: data is undefined
        }
    },
    success: function (data, status) {
        loadCase(ID, data);
    },
    error: function (data) {
    }
});
}

【问题讨论】:

  • 只是出于好奇,您真的需要使用 WebMethod 吗?创建 Web API 或 MVC 控制器是一种选择吗?这会让你的事情变得更容易......
  • @RuiJarimba 是的。这是工作的要求。但老实说,我不知道 Web API 或 MVC(我还是 C# 新手)。
  • 我们只是说.aspxasmx 文件中的[WebMethod] 方法是做这种事情的旧方法,应该避免(如果可能的话)。 REST API 的最佳选择是 ASP.NET Web API

标签: javascript c# ajax


【解决方案1】:

你可以这样做。使用 Web API 而不是 Web 方法并返回 HttpResponseMessage 而不是 case

public HttpResponseMessage CreateNewCase(int id)
{
 try
 {
    Case caseResponse = new Case();

    //some process about checking if the ID exists and loading other data

    if(idCount > 0)
    {
       return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
    }
    else
    {
     return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
    } 
 }
 catch (Exception ex)
 {
    return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
 }
}

【讨论】:

  • 感谢您的回答。但我收到一个错误An object reference is required for the non-static field, method, or property 'Page.Request'
  • 对不起。没有意识到这是WebAPI。现在我得到一个错误:'HttpRequest' does not contain a definition for 'CreateResponse' and no extension method 'CreateResponse' accepting a first argument of type 'HttpRequest' could be found
  • 尝试使用 System.Net.Http.HttpRequestMessage 和 ApiController.Request
  • 你的控制器类应该继承自 ApiController
【解决方案2】:

如果您想使用 web 方法方法,请更改 ajax 并尝试解析 errro 函数中的错误,如下所示

function newCase() {

$.ajax({
   url: 'Default.aspx/CreateNewCase',
   data: JSON.stringify(
    {id: ID }
   ),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",    
success: function (data, status) {
    loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
   if(jqXHR.status =="409" ){
   var data= jqXHR.responseJSON;
    loadCase(ID, data);
   }
   else 
   {
   console.log(textStatus);
   }    
  }
  });
 }

【讨论】:

  • 现在;我从 'var data= jqXHR.responseJSON;' 得到错误数据没有定义。可能是因为状态 409,http 阻塞了数据?
  • 用户 JSON.stringify(jqXHR.responseText);
猜你喜欢
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2020-08-19
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多