Hier ist mein Api-Controller I 2010 in Visual Studio mit dem Assistenten erstellt:Wie sollte mein Ajax-Anruf aussehen - jQuery, MVC4?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ApiTest2MvcApplication.Models;
using System.Linq.Expressions;
using ApiTest2MvcApplication.DTOs;
using System.Threading.Tasks;
using System.Web.Http.Description;
using System.Web.Mvc;
namespace ApiTest2MvcApplication.Controllers
{
public class Default1Controller : ApiController
{
private UsersContext db = new UsersContext();
// GET api/Default1
public IEnumerable<UserProfile> GetUserProfiles()
{
return db.UserProfiles.AsEnumerable();
}
// GET api/Default1/5
public UserProfile GetUserProfile(int id)
{
UserProfile userprofile = db.UserProfiles.Find(id);
if (userprofile == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return userprofile;
}
// PUT api/Default1/5
public HttpResponseMessage PutUserProfile(int id, UserProfile userprofile)
{
if (ModelState.IsValid && id == userprofile.UserId)
{
db.Entry(userprofile).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
// POST api/Default1
[AcceptVerbs("POST")]
public HttpResponseMessage PostUserProfile(UserProfile userprofile)
{
System.Diagnostics.Debug.WriteLine("Username: " + userprofile.UserName);
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userprofile);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = userprofile.UserId }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
// DELETE api/Default1/5
public HttpResponseMessage DeleteUserProfile(int id)
{
UserProfile userprofile = db.UserProfiles.Find(id);
if (userprofile == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.UserProfiles.Remove(userprofile);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, userprofile);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Und hier ist meine Ansicht mit jQuery Ajax-Aufruf:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<input type="button" id="postBtn" value="Post"/>
<script src="../../Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var testPost = (function() {
return {
usePost: function (e) {
//e.defaultPrevented();
$.ajax({
contentType: 'application/json; charset=utf-8',
method: "POST",
url: "/api/Default1",
data: { UserId: 1000, UserName: "Vlado", Email: "[email protected]", Phone: "(02) 1212121", NameAndSurname: "Vlade Edalv" },
dataType: "json",
beforeSend: function (jqXHR, settings) {
console.log("Sending data...");
},
success: function (data, textStatus, jqXHR) {
console.log("status: " + textStatus + ", data: " + JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Status: " + textStatus + ", Error: " + errorThrown);
}
});
},
pageReady: function() {
}
};
}());
$.ready(testPost.pageReady);
$("#postBtn").on('click', testPost.usePost);
</script>
Das Problem, das ich konfrontiert ist, in Browser-Netzwerk Ich sehe, dass dieser Aufruf immer noch die GET-Methode anstelle von POST verwendet. Daher erhalte ich alle Daten, die in der UserProfile-Tabelle aufgelistet sind, als Antwort auf diese GET-Anforderung.
Ich weiß, dass das Problem Routing ist, aber ich weiß nicht, wo Sie hinzufügen und was hinzuzufügen. Kann mir jemand sagen, wie ich meine API-Controller-POST-Methode verwenden kann?