【问题标题】:How can I pass an object (class) to Rest Service如何将对象(类)传递给 Rest Service
【发布时间】:2020-06-03 19:02:30
【问题描述】:

在我的 REST 服务中,我有以下内容: 资产控制器:

// GET: <AssetController>
[HttpGet("{companyID}/{machineName}")]
public Asset Get(int companyID, string machineName)
{
    Database db = new Database(configuration.ConnectionString);

    //DataSet ds = db.executeFunctionSelect("fngetallassets2()");
    DataSet ds = db.executeViewSelect("tblasset where LOWER(name) = '" + machineName.ToLower() + "'");
    //DataSet ds = db.executeDataSetProc("getallassets", null);            

    DataTable table = ds.Tables[0];
    DataRow row = table.Rows[0];

    Asset asset = new Asset
    {
        ID = int.Parse(row["ID"].ToString()),
        CompanyID = int.Parse(row["Company_ID"].ToString()),
        Name = row["Name"].ToString(),
        IPAddress = row["IP_Address"].ToString(),
        CreateDate = DateTime.Parse(row["Create_Date"].ToString()),
        IsActive = bool.Parse(row["Is_Active"].ToString())
    };

    return asset;
}

这很好......它是我需要帮助的 PUT

   // PUT /<AssetController>/5
        // Insert record into the database
        [HttpPut("{asset}")]
        public void Put([FromBody] string asset)
        {
            Database db = new Database(configuration.ConnectionString);
            db.executeNonQuery("sp_AssetInsert", null);
        }

在这里,我试图(以某种方式)传递相同的资产类别

在调用windows窗体中我使用这种方式调用PUT方法:

 public void InsertAsset(Asset asset)
        {
            ArrayList parameters = new ArrayList
            {
                asset.Name,
                asset.IPAddress
            };

             RestClient client = new RestClient("https://localhost:5001/Asset/");
             RestRequest request = new RestRequest(Method.PUT);
        request.AddJsonBody(asset);
        IRestResponse<List<string>> response = client.Execute<List<string>>(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {

            }

我收到关于 Response.StatusCode = unsupportedmedia 或类似内容的错误。 我需要知道如何序列化或以某种方式传递它的类或 JSON 字符串或其他任何东西......

有人可以帮我弄清楚如何调用 PUT 方法,因为我有很多这样的事情要做。

【问题讨论】:

  • 您可能应该在请求正文中发送参数,而不是作为路由参数。
  • 其次是@SBFrancies 所说的 - 资产不应该在您的路径中。如果您的路径中必须有 Asset 对象,则至少需要对其进行 Base64 编码以使 URL 有效。但请将资产负载放入您的请求正文中。
  • OT:您可以直接将这些行值转换为 int,而不是 ToString 后跟 Parse。干净多了
  • [FromBody] Asset asset?但是不要将 Entity Framework 实体用作 DTO,将数据库与 API 解耦。
  • Asset 是一个类对象,而不是一个实体...我传递类对象来获取和保存数据。

标签: c# rest


【解决方案1】:

这是用于完成这项工作的调用和接收代码。

调用:

RestClient client = new RestClient("https://localhost:5001/Asset/");

            RestRequest request = new RestRequest(Method.PUT);
            request.AddJsonBody(asset); <-- Asset is a class object
            RestResponse response = (RestResponse)client.Execute(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {

            }

接收代码:

// PUT /<AssetController>/5
        // Insert record into the database
        [HttpPut]
        public void Put([FromBody] Asset asset)
        {
            Database db = new Database(configuration.ConnectionString);
            db.executeNonQuery("sp_AssetInsert", null);
        }

我需要将 [FromBody] 字符串资产更改为 [FromBody] 资产资产

【讨论】:

    【解决方案2】:

    传参有几种方式:

    1. 作为 url 路由,即https://localhost:5001/Asset/42/MyCompanyName
    2. 作为url参数http://localhost:5001/Asset?companyID=42&machineName=companyname
    3. 在正文中,通常作为 json 序列化对象

    当您在[HttpPut("{paramaters}")] 中指定路由时,您正在指定选项1。您可以使用参数上的FromBodyFromUrl 属性来控制这一点。像数字和字符串这样的简单参数通常是 URL 的一部分,而像 Asset 这样的复杂对象可能更容易在正文中传递。

    另见

    【讨论】:

    • 我想了解有关如何传递资产对象的更多信息:这是我用来尝试传递资产对象的代码 RestClient client = new RestClient("localhost:5001/Asset/"); RestRequest request = new RestRequest(Method.PUT); request.AddHeader("Accept", "application/json"); request.AddJsonBody(asset); RestResponse response = (RestResponse)client.Execute(request); if (response.StatusCode == HttpStatusCode.OK) { } 我已经更新了上面文本中的代码。
    猜你喜欢
    • 2015-04-10
    • 2012-07-30
    • 2012-07-20
    • 2014-06-23
    • 2013-01-31
    • 2014-01-06
    • 1970-01-01
    • 2014-06-24
    • 2011-12-17
    相关资源
    最近更新 更多