本文介绍了C#Web Api 2 PUT和POST请求不受支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我已经让我的ASP.NET web API正确地为员工执行GET请求,并使用JQuery填充其中的字段。删除请求也起作用,但我一直收到:
Message=The requested resource does not support http method 'PUT'.
出现405 http方法不允许错误。这可能是因为我的PUT/POST请求包括对象、字符串作为参数,而不是简单地获取要获取和删除的URL的ID。这是一个从一个站点到另一个站点的跨域请求,因此我的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>
以下是我的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" }
);
我的控制器:
[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);
}
}
最后(很抱歉代码量太大),我的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);
}
});
推荐答案
根据this article,Web API将尝试从URL获取字符串值,您将在请求正文中提供该值。
尝试将您的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);
}
});
您不需要用[FromBody]注释EmployeeModel,因为它是一个复杂的对象。默认情况下,Web Api默认序列化将尝试从正文中获取它。
注意:如果netID是更新资源的用户的ID,则最好在EmployeeModel中有一个属性UpdatedBy。遵循REST原则,PUT请求在URL中应具有资源的ID
这篇关于C#Web Api 2 PUT和POST请求不受支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!