Web 表单的 Web Api 控制器无法使用 POST 动词

Web Api controller of a webforms not working to POST verb

由于我是 webAPI 的新手,我搜索了很多与此相关的问题,但没有一个符合我的情况。 我在 webforms project.In Post 方法中有一个 webApi 控制器,一些数据被插入到数据库中。我是按照 here 的指示完成的。按照他们提到的方式完成所有操作,但控制器的 POST 方法不起作用

注:- 1) 如果我使用具有相同代码的 Webservice(SOAP) 而不是 webAPI,它工作正常。 2)如果我使用邮递员来测试它的作品。 3) 如果我在前端使用简单的 html 页面,它会显示 HTTP 错误 405.0 - 方法不允许

这是我的 aspx 页面

<body>
    <form id="form1" runat="server">
    <div>
    <input type="text" id="name" />
    <input type="text" id="lastname" />
        <button id="submit"></button>

        <script>

        $(document).ready(function () {
            $('#submit').click(function () {

                var appointment = {};
                appointment.FirstName = $('#name').val();
                appointment.LastName = $('#lastname').val();



                $.ajax({

                    url: '/api/Appointment',
                    method: 'POST',
                    dataType: 'JSON',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ 'app': appointment }),
                    success: function ()
                    {
                        alert('success');
                    },
                    error:function(xhr,err)
                {
                        alert(xhr.responseText);
                }
                });

            });

        });
    </script>
    </div>
    </form>
</body>

这是我的控制器:

 public class AppointmentController : ApiController
    {

        // POST api/<controller>
        [HttpPost]
        public void Post([FromBody]Appointment app)
        {
            app.Save();
        }

    }

这是Global.asax

public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = System.Web.Http.RouteParameter.Optional });
        }
    }

这是我的 web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="connection" connectionString="server=MACLINKSERVER\MSSQL_DEV;Database=DB_A1DE96_Smartgdx;UID=sa;PWD=123;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <webServices>
      <protocols>
        <add name="HttpGet" />
        <add name="HttpPost" />
      </protocols>
    </webServices>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
</configuration>

Post约会

data: JSON.stringify(appointment),

因为这是行动所期望的。

此外,该操作还需要 return 一个有效的响应,如原始问题中链接的文档中所示。

public class AppointmentController : ApiController {
    // POST api/<controller>
    [HttpPost]
    public IHttpActionResult Post([FromBody]Appointment app) {
        app.Save();
        return Ok();
    }
}

这里的假设也是 Appointment 有一个无参数的构造函数,它将允许模型绑定器正确地绑定和填充模型。