MVC Web API posting JSON data gives me a 404

2020-04-17 07:17发布

问题:

I have a Web API in MVC4. I'm getting a 404 when posting data using ajax and I don't understand why.

LanguageController:

[AcceptVerbs("POST")]
public void Delete(string id)
{
    Guid guid = Guid.Parse(id);

    Language language = db.Languages.Find(guid);
    db.Languages.Remove(language);
    db.SaveChanges();

}

Routing:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

And javascript (using AngularJS):

this.delete = function (lang) {
    $http({
        method: "POST",
        url: "/api/language/delete",
        data: JSON.stringify({ id: lang.id })
    })
    .success(function (response) {
        return true;
    })
    .error(function (response) {
        return false;
    });
};

I get this error message:

**{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:32166/api/language/delete'.","MessageDetail":"No action was found on the controller 'Language' that matches the request."}**

I just don't understand why, it looks like it should work. I feel like I'm missing a piece of vital information.

回答1:

Cuong Le's answer is the correct way make delete requests, however it wasn't an answer to my question. This was more to do with working out posting data to the server with MVC and Angular so the delete action was immaterial.

The mistake I was making was assuming that MVC's routing would pull the ID from the posted data.

What I did was add my Language model as a parameter on my method:

[AcceptVerbs("POST")]
public void Delete(Language lang)
{    
    Language language = db.Languages.Find(lang.ID);
    db.Languages.Remove(language);
    db.SaveChanges();    
}

This solves my 404 and leaves me feeling rather stupid as it's pretty obvious now that the routing wouldn't just know to pull the ID out... I could probably improve it by using a view model instead of my Language model.



回答2:

The file name of the code public void Delete(string id) should be named "languageController". Pls check the name

Also, the better way to use Delete action should be in "Delete" rather than "Post"