简体   繁体   中英

How to configure c# WebApi HTTP DELETE response

I have an api controller for a WebApi application that works to return a GET request, but not for DELETE or PUT. The controller is:

    // 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;
    }

For the following request from a webpage from another server..

<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>

I get a response of:

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

I tried to route this in my WebApiConfig, and I believe the problem lies here, I am just unsure how to route this DELETE action here:

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 }
        //);
    }
}

Are you sure IIS is configured to handle PUT and DELETE verbs? status 405 indicates the method is not allowed, please follow the link here to add the support.

Hope it helps.

Maybe you have already changed this:

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

to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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