我尝试了在 Stack Overflow 上找到的所有解决方案,但没有成功。
我的 web.config 包含:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, GET, DELETE, PUT, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
我总是得到:
在我的应用程序中,我做了:
this.model.save({ firstname: name[0], lastname: name[1] });
我的收藏是:
app.AttendeeCollection = Backbone.Collection.extend({
url: 'http://test-backbone/attendee',
model: app.AttendeeModel
});
我的C#:
[AcceptVerbs(HttpVerbs.Put)]
public JsonResult Index(int id, Attendee updatedAttendee)
{
var attendee = db.Attendees.Where(a => a.id == id).FirstOrDefault();
attendee.firstname = updatedAttendee.firstname;
attendee.lastname = updatedAttendee.lastname;
db.SaveChanges();
return Json(attendee, JsonRequestBehavior.DenyGet);
}
问题
- 任何的想法?
- 有没有办法用 POST 替换 PUT 和 DELETE?:(
完整控制器(MVC 4、Internet 应用程序、本地 IIS、Win 7)
using System.Linq;
using System.Web.Mvc;
using AttendeeManager.Models;
namespace AttendeeManager.Controllers
{
public class AttendeeController : Controller
{
AttendeeEntities db = new AttendeeEntities();
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Index(int? id)
{
if (id.HasValue)
{
var attendee = db.Attendees
.Where(a => a.id == id)
.Select(a => new { id = a.id, firstname = a.firstname, lastname = a.lastname })
.FirstOrDefault();
return Json(attendee, JsonRequestBehavior.AllowGet);
}
else
{
var attendees = db.Attendees
.Select(a => new { id = a.id, firstname = a.firstname, lastname = a.lastname })
.ToList();
return Json(attendees, JsonRequestBehavior.AllowGet);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Index(Attendee createdAttendee)
{
db.Attendees.AddObject(createdAttendee);
db.SaveChanges();
return Json(createdAttendee, JsonRequestBehavior.DenyGet);
}
[AcceptVerbs(HttpVerbs.Put)]
public JsonResult Index(int id, Attendee updatedAttendee)
{
var attendee = db.Attendees.Where(a => a.id == id).FirstOrDefault();
attendee.firstname = updatedAttendee.firstname;
attendee.lastname = updatedAttendee.lastname;
db.SaveChanges();
return Json(attendee, JsonRequestBehavior.DenyGet);
}
[AcceptVerbs(HttpVerbs.Delete)]
public JsonResult Index(int id)
{
var attendee = db.Attendees.Where(a => a.id == id).FirstOrDefault();
db.Attendees.DeleteObject(attendee);
db.SaveChanges();
return Json(attendee, JsonRequestBehavior.DenyGet);
}
}
}