嗨,我正在尝试删除记录(httpdelete)。控制器中的方法不触发,而获取405方法不允许错误。
下面的jQuery
function deleteContract(contractId) {
var contract = new Object();
contract.ContractID = "ContractId";
$.ajax({
async: true,
type: 'DELETE',
data: contract,
dataType: "json",
url: 'http://localhost:4233/api/Contract/DeleteContractById/' + contractId,
}).done(function (data, textStatus, xhr) {
alert("deleted successfully")
}).error(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText || textStatus);
})
}
下面的控制器
// DELETE: api/Contract/5
[ResponseType(typeof(Contract))]
[AllowAnonymous]
[HttpDelete]
[ActionName("DeleteContractById")]
//[Route("api/Contract/{id}")]
[AcceptVerbs("DELETE")]
public HttpResponseMessage DeleteContract(Guid id)
{
Contract contract = db.Contract.Find(id);
if (contract == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Strata.Remove(contract);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, contract);
}
webapiconfig
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "GET", id = RouteParameter.Optional }
);
}
Web配置下面
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<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>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</customHeaders>
</httpProtocol>
</system.webServer>
当我使用Fiddler打电话时,其工作正常。让我知道我是否错过了代码中的任何设置。
谢谢dev
您是否尝试使用异步语法?喜欢
public async Task<HttpResponseMessage> DeleteStrata(Guid id)
...
await db.SaveChangesAsync()
当我使用的方法不是API期望的时候,我已经获得了405。我确实注意到了一些事情,尽管我不确定这些是根本的问题:
- API上的动作名称拼写错误,应删除合同(已取代合同)。
- DeleteCntract函数正在通过一个身体。API方法不希望身体(数据)。
- 该路线已设置为期望GUID ID。合同的价值是否传递给了有效的GUID?
我们通过进行以下更改找到了解决方案
web.config
<customHeaders>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Request-Headers" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>
startup.auth.cs
在班级级别声明以下
[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll); // newly added this require to "Install-Package Microsoft.Owin.Cors"
}
控制器
[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public class ContractController : ApiController
{
}
webapi.config
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));
// Web API routes
config.MapHttpAttributeRoutes();
// Controllers with Actions
// To handle routes like `/api/VTRouting/route`
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "GET", id = RouteParameter.Optional }
);
}
}
这就是它开始工作的全部。