asp.net web api2 - Creating post web api 2 actions -
i attempting should straight forward, honest pretty far @ moment , driving me bit mad.
i've been consuming actions in webapi, i'm trying create post actions in order keep mvc controllers clean can't life of me figure out why actions work expected post action results in 404
using microsoft.aspnet.authorization; using microsoft.aspnet.mvc; using tamweb.models.api; namespace tamweb.controllers.api { [authorize] [route("api/[controller]")] public class admincontroller : controller { [httppost] public bool updatedetails([frombody]detailsviewmodel model) { return false; } } } using system; namespace tamweb.models.api { public class detailsviewmodel { public string firstname { get; set; } public string lastname { get; set; } } }
the api controller simple gets , per several other api questions instead of using string parameters i've created model object , follow other answers , little out of date documentation can find consume api follows:
$(function() { var firstname = $('#firstname').val(); var lastname = $('#lastname').val(); $.ajax({ url: "api/admin/updatedetails", type: "post", data: json.stringify([firstname, lastname]), success: function(data) { console.log(data); }, error: function() { console.log("error") } }); });
as far can tell "should" work, fiddler keeps telling me url doesn't exist i'm @ loss whats wrong.
hopefully answer can deal question.
1.first issue have use "apicontroller" instead "controller"
2. [authorize] <-- have token key , using data webapi
as following code, share me simple code without authorize,i wish can solve problems client code
$("#read1").click(function () { $.support.cors = true; $.ajax({ crossdomain: true, url: 'http://localhost:43520/api/banners/', datatype: "json", contenttype: "application/json; charset=utf-8", data: { id: 123 }, type: 'post', error: function (xhr, status, errorthrow) { alert(xhr.status); }, success: function (data) { alert(json.stringify(data)); } }); });
server code
// get: api/banners/5 [responsetype(typeof(banners))] public ihttpactionresult getbanners(int id) { banners banners = db.banners.find(id); if (banners == null) { return notfound(); } return ok(banners); }
Comments
Post a Comment