【发布时间】:2020-05-07 20:15:12
【问题描述】:
我正在尝试将 ASP.NET Core 3 api 与 React-Admin 连接。到目前为止,我可以列出数据库中的条目并显示一条记录——显然这两种 GET 方法工作正常。 (坚持这个example)
当我尝试使用 POST 方法创建记录时,我收到 400 Bad Request 并且无法跟踪问题。
我的 App.js 看起来像这样:
import simpleRestProvider from 'ra-data-simple-rest';
import realApi from './dataProvider/myDataProvider';
const dataProvider = simpleRestProvider('api/');
const App = () =>
<Admin
dashboard={Dashboard}
dataProvider={realApi}
>
<Resource name={projects.basePath} {...projects.crud} />
...
</Admin>;
我有从官方 react-admin 教程复制的自定义 dataProvider
export default (type, resource, params) => {
let url = '';
const options = {
headers: new Headers({
Accept: 'application/json',
"Content-Type": 'application/json; charset=utf-8',
}),
};
let query = "";
switch (type) {
case GET_LIST: {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([
(page - 1) * perPage,
page * perPage - 1,
]),
filter: JSON.stringify(params.filter),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
break;
}
case GET_ONE:
url = `${apiUrl}/${resource}/${params.id}`;
break;
case CREATE:
url = `${apiUrl}/${resource}`;
options.method = 'POST';
options.body = JSON.stringify(params.data);
break;
case UPDATE:
url = `${apiUrl}/${resource}/${params.id}`;
options.method = 'PUT';
options.body = JSON.stringify(params.data);
break;
case UPDATE_MANY:
query = {
filter: JSON.stringify({ id: params.ids }),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
options.method = 'PATCH';
options.body = JSON.stringify(params.data);
break;
case DELETE:
url = `${apiUrl}/${resource}/${params.id}`;
options.method = 'DELETE';
break;
case DELETE_MANY:
query = {
filter: JSON.stringify({ id: params.ids }),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
options.method = 'DELETE';
break;
case GET_MANY: {
query = {
filter: JSON.stringify({ id: params.ids }),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
break;
}
case GET_MANY_REFERENCE: {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([
(page - 1) * perPage,
page * perPage - 1,
]),
filter: JSON.stringify({
...params.filter,
[params.target]: params.id,
}),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
let headers;
return fetch(url, options)
.then(res => {
headers = res.headers;
debugger
return res.json();
})
.then(json => {
switch (type) {
case GET_LIST:
case GET_MANY_REFERENCE:
if (!headers.has('content-range')) {
throw new Error(
'The Content-Range header is missing in the HTTP Response. The simple REST data provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?'
);
}
return {
data: json,
total: parseInt(
headers
.get('content-range')
.split('/')
.pop(),
10
),
};
case CREATE:
return { data: { ...params.data, id: json.id } };
default:
return { data: json };
}
});
};
最后是 ASP.NET 控制器:
[Route("api/[controller]")]
[ApiController]
public abstract class RaController<T> : ControllerBase, IRaController<T> where T : class, new()
{
protected readonly IDveDbContext _context;
protected DbSet<T> _table;
public RaController(IDveDbContext context)
{
_context = context;
_table = _context.Set<T>();
}
[HttpGet("{id}")]
public async Task<ActionResult<T>> Get(int id)
{
var entity = await _table.FindAsync(id);
if (entity == null)
{
return NotFound();
}
return entity;
}
[HttpPost]
public async Task<ActionResult<T>> Post(T entity)
{
_table.Add(entity);
await _context.SaveChangesAsync();
var id = (int)typeof(T).GetProperty("Id").GetValue(entity);
return Ok(await _table.FindAsync(id));
}
}
以及确切的 ProjectsController
[Route("api/[controller]")]
public class ProjectsController : RaController<Project>
{
private IProjectService projectService;
public ProjectsController(IProjectService projectService, IDveDbContext dbContext)
: base (dbContext)
{
this.projectService = projectService;
}
}
我一直在寻找解决方案,但找不到任何解决方案。如果有人提示问题可能出在哪里,或者提供一个成功地将 ASP.Net Core 与 React-Admin 集成的示例,我将非常感激!
【问题讨论】:
标签: asp.net reactjs asp.net-core-webapi react-admin asp.net-core-3.1