首页 > 解决方案 > Web Api 2.0 在邮递员中工作但不在 HTML 页面中

问题描述

这是我在.Net中用于web api 2.0的控制器代码当我使用邮递员时它工作正常但是当我从HTML页面调用它时我得到错误No HTTP resource was found that matches the request URI 我做错了什么?

控制器代码

[HttpPost]
public IHttpActionResult GetCustomerName (string num)
{
   return Json(new
   {
      success = true,
      message = "My Name "+ num,
   });
}

HTML 代码

$.ajax({
   url: "http://localhost:10000/api/CFP/GetCustomerName",
   type: "POST",
   data: {
            'num': '123'
         },
   contentType: 'application/json; charset=utf-8',
   success: function (response) {
      alert(response.message);
   },
   error: function (xhr, error, thrown) {
      alert(xhr.responseText);
   }
});

错误截图
错误截图

邮递员截图
在此处输入图像描述

标签: .netajaxpostmanasp.net-web-api2

解决方案


$.ajax({
   url: "http://localhost:10000/api/CFP/GetCustomerName",
   type: "POST",
   data: JSON.stringify({
            'num': '123'
         }),
   contentType: 'application/json; charset=utf-8',
   success: function (response) {
      alert(JSON.stringify(response));
   },
   error: function (xhr, error, thrown) {
      alert(xhr.responseText);
   }
});

您可以通过对数据进行字符串化来尝试上面的代码吗

您可以从邮递员本身创建正确的代码:

在此处输入图像描述

只需 clikc 代码并找到等效的 ajax 代码


推荐阅读