繁体   English   中英

REST API的一个功能不起作用,其余功能起作用

[英]One function of a REST API doesn't work but the rest do

这个问题有点令人困惑。 我已经使用Visual Studio在Web API 2中编写了RESTful API。 我已经编写了一些函数,例如(GetMailbox,GetUser,Logout),一些POST和一些GET。 这些全部工作正常。 我添加了另一个名为SendMessage的POST函数。 但是,这不起作用,如果我尝试将数据发布到URL,它将返回“发生错误”。 我添加了调试代码(日志编写,文件编写等),以确定该功能出了什么问题。 但是,即使写入日志是函数中的第一行代码,也不会写入日志,也不会写入文件。 任何帮助解释这种奇怪的情况将不胜感激。 我还提供了该功能以供参考。

功能:

    [HttpPost]
    public IHttpActionResult SendMessage(SendMessage sendMessage)
    {
        System.Diagnostics.EventLog.WriteEntry("REST API", "Entered SendMessage");
        File.WriteAllText(@"C:\inetpub\wwwroot\rest\debug.txt", "Entered SendMEssage");
        IEnumerable<string> headerValues;
        string token = string.Empty;
        if (Request.Headers.TryGetValues("Token", out headerValues))
        {
            token = headerValues.FirstOrDefault().ToString();
        }
        if (token == string.Empty)
        {
            return BadRequest("Missing Header: Token");
        }
        try
        {
            if (sendMessage.Attachments == null)
                sendMessage.Attachments = new string[0];
            if (sendMessage.AttachmentNames == null)
                sendMessage.AttachmentNames = new string[0];
            string tos = "", ccs = "", bccs = "";
            foreach (string str in sendMessage.To)
                tos += str + ",";
            foreach (string str in sendMessage.Cc)
                ccs += str + ",";
            foreach (string str in sendMessage.Bcc)
                bccs += str + ",";
            System.Diagnostics.EventLog.WriteEntry("REST API", sessionKey + " " + tos + " " + ccs + " " + bccs + " " + sendMessage.Attachments.Length + " " + sendMessage.AttachmentNames[0] + " " + sendMessage.Body + " " + sendMessage.Subject);
            return Ok(lib.SendMessage(token,sendMessage.To,sendMessage.Cc,sendMessage.Bcc,sendMessage.Attachments,sendMessage.AttachmentNames,sendMessage.Body,sendMessage.Subject));
        }
        catch (Exception ex)
        {
            return BadRequest(ex.InnerException.Message);
        }
    }

函数调用:

POST /rest/api/Mailbox/SendMessage HTTP/1.1
Host: 192.168.10.160:80
Content-Type: application/json
Token: 74362B94933C4FAFA8203411257F1757
Cache-Control: no-cache
Postman-Token: 7402852a-d3f6-7c56-2b44-516dd6bd099c

{
  "To": ["email@email.com"],
  "Cc": [],
  "Bcc": [],
  "Attachments": [],
  "AttachmentNames": [],
  "Body": "Test no attachment",
  "Subject": "Test no attachment"
}

正如Shekhar所说,请尝试重命名您的操作:

[HttpPost]
public IHttpActionResult Send(SendMessage msg)
{

}

似乎是绑定/请求参数错误。

退后一步,从婴儿的脚步开始。

  • 删除方法的内容,参数并检查是否有空白帖子到达您的控制器。
  • 添加一个简单的参数(字符串或整数),然后再次到达您的控制器;
  • 添加一个复杂的对象并重复;
  • 最后添加方法内容;

您肯定会比您想象的早发现问题(可能是SendMessage类结构甚至请求标头出现问题...)

该解决方案最终比我预期的要容易。 但是,找到解决方案很困难。 事实证明,该方法调用包含另一个对目标系统上不存在的库的调用。 始终检查您的引用,并确保将它们设置为“本地副本:true”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM