[英]How to make Post operation using .net core and neo4j
我是 .Net Core 和 Neo4j 的新手。 我想使用 Neo4jClient 为 CRUD 操作制作 Wep Api。我有一个 Book 类及其控制器。 我还有 Author 及其控制器类。 我想进行Post操作,但我不能。 邮递员返回 BadRequest()。 那么我该如何解决这个问题? 问题是什么?
这是我的 Book.cs 源代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NEO4j.Models
{
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public List<string> CategoryCodes { get; set; }
}
}
图书控制器.cs
using Microsoft.AspNetCore.Mvc;
using NEO4j.Models;
using NEO4j.Services;
using Neo4jClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace NEO4j.Conrollers
{
[Route("api/book")]
public class BookController : Controller
{
private static int uniqueId=1;
public string title { get; set; }
public List<string> category { get; set; }
private static BookService bookService;
private static CategoryService categoryService;
static BookController()
{
bookService = new BookService();
categoryService = new CategoryService();
}
[HttpGet]
public ActionResult Get()
{
var graphClient = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "1234");
graphClient.Connect();
var data = graphClient.Cypher
.Match("(m:Book)")
.Return<Book>("m")
.Results.ToList();
return Ok(data.Select(c => new { book = c }));
}
[HttpPost]
public ActionResult Post([FromBody] Book book) {
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "1234");
client.Connect();
if (book == null)
return BadRequest();
if (!ModelState.IsValid)
return BadRequest(ModelState);
var newBook = new Book { Id = uniqueId, Title = title, CategoryCodes = category };
client.Cypher
.Merge("(book:Book { Id: {uniqueId} ,Title:{title},CategoryCodes:{category}})")
.OnCreate()
.Set("book = {newBook}")
.WithParams(new
{
uniqueId =newBook.Id,
title = newBook.Title,
category = newBook.CategoryCodes,
newBook
})
.ExecuteWithoutResults();
uniqueId++;
return Ok(newBook);
}
}
}
仅适用于 ASP.Net Core 部分:
本地主机:63654/api/book {“标题”:“深度学习”,“类别代码”:“5”}
book
为空
您如何提出请求(就您而言, Postman
)很重要 - 这就是我要求您提供的原因。 所以Headers
等很重要。
通过 Postman 发送JSON
:
POST /api/test HTTP/1.1 Host: localhost:63654 Content-Type: application/json Cache-Control: no-cache Postman-Token: 51081616-c62d-c677-b5ab-37d428018db5 {"Title":"Deep Learning", "CategoryCodes": ["1","2","3"]}
注意Content-Type
标题
我们的Book
模型中的CategoryCodes
是一个List
,因此您必须为其值设置一个“列表”(数组),如上所示"CategoryCodes": ["1","2","3"]
嗯..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.