【问题标题】:How to pass void return type into Json如何将 void 返回类型传递给 Json
【发布时间】:2016-11-22 08:15:23
【问题描述】:

请帮助我。如何将消息从 void 传递到返回类型?

WebApi.cs

public void DeleteById(int id)
{
    string meassga = "";
    try
    {
        objser.DeleteBYId(id);
    }
    catch (Exception ex)
    {
        meassga = "" + ex;
    }

}

Mvc.cs

public JsonResult DeleteById(int id)
{
   string meassga = "";
   ss.DeleteBYId(id);
   return Json ( meassga,  JsonRequestBehavior.AllowGet );
}

在这里,我将数据从 mvc 传递到 webApi,并且我想显示从 api 控制器到 mvc json 控件的错误详细信息

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    你不能。你有几个选择,改变你的 webapi 方法以返回一个字符串,或者像这样抛出异常:

    public void DeleteById(int id)
        {
            try
            {
                objser.DeleteBYId(id);
            }
            catch (Exception ex)
            {
                throw new Exception($"Exception in DeleteById({id}) - {ex.Message}", ex);
            }
        }
    

    然后在控制器中:

    public JsonResult DeleteById(int id)
        {
            try 
            {
               ss.DeleteBYId(id);
               return Json ("Deleted successfully", JsonRequestBehaviour.AllowGet);
            }
            catch(Exception ex)
            {
              return Json ( ex.Message,  JsonRequestBehavior.AllowGet );
            }
        }
    

    ...类似。在不抛出异常的情况下,另一种常见的策略是创建一个这样的返回类:

    public class ApiResult<T>
    {
       public string Message { get; set; }
       public T Result { get; set; }
       public bool Success { get; set; }
    }
    

    并将其实现为所有 api 调用返回的东西。

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 2018-06-23
      • 2022-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多