【问题标题】:call c# method with parameters from js ajax使用来自 js ajax 的参数调用 c# 方法
【发布时间】:2019-08-27 17:32:23
【问题描述】:

从 js ajax 调用 c# 方法时,我在控制台上收到 404 错误

我尝试了以下方法将数据发送到 c# 方法

data: '{ name: "test" }'
data: JSON.stringify({ 'name': 1234 }),

$.ajax({
    url: "/api/system/AddCertificateFromStore",       
    type: 'POST',
    data: '{ name: "divya" }',
    complete: function (xhr, status) {
    },
    error: function (xhr, status, err) {
    }
    },
    cache: false,
    contentType: "application/json; charset=utf-8",
    processData: false,
    dataType: 'json'

C#方法是这样的

[HttpPost]
public HttpResponseMessage AddCertificateFromStore(string CertificateName)
{
    // Make the web request
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

    return response;
}

希望将参数正确发送到 C# 方法,以便从 js ajax 调用它

【问题讨论】:

  • 当您在浏览器中访问/api/system/AddCertificateFromStore 时会发生什么?
  • 您已经传递了参数名称,并且在您的方法参数中是 CertificateName
  • 另外,您的 javascript 代码无效,您有多余的 }
  • HTTP404: NOT FOUND - 服务器未找到与请求的 URI(统一资源标识符)匹配的任何内容。 (XHR)POST - localhost:15899/api/system/AddCertificateFromStore..this 是我在浏览器控制台上遇到的错误..
  • 好的,所以问题的第一部分是您的 c# 脚本不起作用。你确定你有正确的路径/路由吗?

标签: javascript c# parameters


【解决方案1】:

你应该在你的 C# Action 中添加一个 FromBody 装饰器

[HttpPost] 公共 HttpResponseMessage AddCertificateFromStore([FromBody] string CertificateName) {

【讨论】:

  • 接受这个答案,如果解决了你的问题,它会帮助别人
  • 它现在正在调用该方法(能够在 C# 中打断点)但仍然没有正确传递字符串
  • 当您使用 [FromBody] 装饰器传递字符串参数时,您是在告诉 Web API 将正文内容作为原始字符串读取。因此,如果您想从 de body 访问字符串,您只需将其作为原始值传递,例如 ... type: 'POST', data: "divya", ...
  • 你是如何发出 Ajax 请求的?
  • 添加 FromBody 解决了这个问题......之后的问题是控制器......但就能够在 C# Action 中发送数据 FromBody 帮助......
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2010-09-27
  • 2021-04-29
  • 1970-01-01
  • 2012-05-27
相关资源
最近更新 更多