如何配置c#WebApi HTTP DELETE响应

时间:2015-06-24 17:52:18

标签: c# asp.net ajax asp.net-web-api asp.net-ajax

我有一个用于WebApi应用程序的api控制器,它可以返回GET请求,但不能用于DELETE或PUT。控制器是:

    // DELETE: api/Employees/5
    [HttpDelete]
    [EnableCors(origins: "https://chad-test4.clas.uconn.edu", headers: "*", methods: "*")]
    public HttpResponseMessage Deleteemployee(int id)
    {
        employee employee = db.employees.Find(id);
        var jsonid = employee.id;

        if (jsonid == null)
        {
            var EmpNull = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error: Employee does not exist.");
            EmpNull.Content = new StringContent("{ Error: Employee Null }", Encoding.UTF8, "application/json");
            return EmpNull;
        }

        db.employees.Remove(employee);
        db.SaveChanges();

        var Success = this.Request.CreateResponse(HttpStatusCode.OK, "Success");
        Success.Content = new StringContent("{ Success: Success }", Encoding.UTF8, "application/json");
        return Success;
    }

对于来自其他服务器的网页的以下请求..     

<script>
$(function () {
    $("#Save").click(function () {
        $.ajax({
            type: "Delete",
            crossDomain: true,
            withCredentials: true,
            url: "https://chad-test4.clas.uconn.edu/api/Employees/1",
            dataType: "json",
            success: function (data) {
                console.log("Response recieved");
                console.log("Success: " + JSON.stringify(data));

            },

            error: function() {
                console.log("Failed"+Error.toString())
            }

          //  data: {"id": 1 }
        });
    });
});
</script>

我收到了回复:

XMLHttpRequest cannot load https://uconn.edu/api/Employees/1. Invalid HTTP 
status code 405
create.htm:43 Failedfunction Error() { [native code] }

我试图在我的WebApiConfig中对此进行路由,我相信问题出在这里,我只是不确定如何在此处路由此DELETE操作:

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();

        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.EnableCors();
        var cors = new EnableCorsAttribute("https://chad-dev.clas.uconn.edu", "*", "*");
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );

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

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

2 个答案:

答案 0 :(得分:0)

您确定IIS配置为处理PUT和DELETE谓词吗?状态405表示不允许该方法,请点击链接here添加支持。

希望它有所帮助。

答案 1 :(得分:0)

也许你已经改变了这个:

config.EnableCors();
    var cors = new EnableCorsAttribute("https://chad-dev.clas.uconn.edu", "*", "*");

到此:

var cors = new EnableCorsAttribute("https://chad-dev.clas.uconn.edu", "*", "*");
config.EnableCors(cors);