问题描述
我在MVC4一个Web API。我得到一个404用ajax发布数据时,我不明白为什么。
I have a Web API in MVC4. I'm getting a 404 when posting data using ajax and I don't understand why.
LanguageController:
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();
}
路由:
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);
}
}
和JavaScript(使用AngularJS):
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.
推荐答案
的Cuong乐的答案是正确的方式做删除要求,但它不是一个回答我的问题。这更多的是与制定发布的数据与MVC服务器和角度,以便删除操作是不重要的。
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.
我正在这个错误是假设MVC的路由会从发布的数据拉ID。
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();
}
这解决了我的404,并让我感觉很愚蠢,因为它是pretty明显现在的路由不会只知道拉出来的ID ......我可以通过使用视图模型,而不是可能改进我的语言模型。
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.
这篇关于MVC的Web API发布的JSON数据给了我一个404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!