简体   繁体   English

C#Web Api 2 PUT和POST请求“不支持”

[英]C# Web Api 2 PUT and POST requests “not supported”

So far I have my ASP.NET web api correctly doing a get request for an employee and filling in the fields from that using JQuery. 到目前为止,我已经使我的ASP.NET Web API正确地执行了对员工的get请求,并使用JQuery填写了字段。 The delete request works also but I keep receiving: 删除请求也有效,但我一直收到:

Message=The requested resource does not support http method 'PUT'.

with a 405 http method not allowed error. 405 http方法不允许错误。 This may be because my put/post requests include both an object,string as parameters instead of simply getting the id of the url to GET and DELETE. 这可能是因为我的放置/发布请求同时包含对象,字符串作为参数,而不是简单地将URL的ID获取到GET和DELETE。 This is a cross-origin request from one site to another so I have enableCors() in my web.config file as well as the removing of WEBDAV: 这是从一个站点到另一个站点的跨域请求,因此我的web.config文件中有enableCors()以及删除了WEBDAV:

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule" />
  <remove name="FormsAuthentication" />
</modules>
<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="https://chad-dev.clas.uconn.edu" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="WebDAV" />
  <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>

Here is my WebApiConfig Register function: 这是我的WebApiConfig注册函数:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {  id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            "WithAction",
            "api/{controller}/{action}/{id}",
            new { controller = "Commitments", action = "GetCommitment" }
        );

My controller: 我的控制器:

[HttpPut]
    public IHttpActionResult PutEmployee([FromBody]EmployeeModel employeeModel, string netId)
    {     
        var chadResult = new CLASWebApiResponse
        {
            Success = true,
            ResponseMessage = "Success",
            Data = null
        };
        try
        {
            employee employeeUpdate = masterDb.employees.Find(employeeModel.Id);

            if (employeeUpdate == null)
            {
                chadResult.ResponseMessage = "Employee not found";
                chadResult.Success = false;
                return Ok(chadResult);
            }

            employeeUpdate.netid = employeeModel.NetId;
            employeeUpdate.enumber = employeeModel.Enumber;
            employeeUpdate.peoplesoft = employeeModel.Peoplesoft;
            employeeUpdate.email = employeeModel.Email;
            employeeUpdate.tenure_year = employeeModel.TenureYear;
            employeeUpdate.tenure_indicator = employeeModel.TenureIndicator;
            employeeUpdate.hire_date = employeeModel.HireDate;
            employeeUpdate.gender = employeeModel.Gender;
            employeeUpdate.birth_date = employeeModel.BirthDate;
            employeeUpdate.updated_by = netId;
            masterDb.SaveChanges();

            chadResult.Success = true;
            chadResult.ResponseMessage = "Success";
            return Ok(chadResult);
        }

        catch (Exception e)
        {
            chadResult.ResponseMessage = e.Message;
            chadResult.Success = false;
            return Ok(chadResult);
        }
    }

And finally (sorry for the amount of code), my ajax request: 最后(抱歉,代码量),我的ajax请求:

$.ajax({
            type: "PUT",
            url: "https://chad-test4.clas.uconn.edu/api/Employees/PutEmployee",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({employeeModel:employeeData, netId:'22'}),
            traditional: true,
            success: function() {
                console.log(employeeModel);
                alert("Saved Successfully.");
            },
            error: function(response) {
                console.log(employeeModel);
                alert("Employee data failed to save to server. Error message: " + jQuery.parseJSON(response.responseText).Message);
            }
        });

According to this article Web api will try to get the string value from the URL and you are providing it on the request body. 根据本文的介绍, Web api将尝试从URL中获取字符串值,并且您将在请求正文中提供它。

Try to change your ajax call to: 尝试将您的ajax调用更改为:

$.ajax({
        type: "PUT",
        url: "https://chad-test4.clas.uconn.edu/api/Employees/PutEmployee?netId=22",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({employeeModel:employeeData}),
        traditional: true,
        success: function() {
            console.log(employeeModel);
            alert("Saved Successfully.");
        },
        error: function(response) {
            console.log(employeeModel);
            alert("Employee data failed to save to server. Error message: " + jQuery.parseJSON(response.responseText).Message);
        }
    });

You wouldn't need to annotate EmployeeModel with [FromBody], as it is a complex object. 您不需要用[FromBody]注释EmployeeModel,因为它是一个复杂的对象。 Web Api default serialization will try to get it from the body by default. 默认情况下,Web Api默认序列化将尝试从正文中获取它。

NOTE: If netID is the ID of the user updating the resouce it is better to have a property UpdatedBy in EmployeeModel. 注意:如果netID是更新资源的用户的ID,最好在EmployeeModel中有一个属性UpdatedBy。 Following REST principles, PUT requests should have the ID of the resource in the URL 遵循REST原则,PUT请求应在URL中具有资源的ID

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

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