web api url与ravenDb Id格式冲突

本文关键字:Id 格式 冲突 ravenDb api url web | 更新日期: 2023-09-27 18:28:41

我在一个Asp.net Web api 2项目中使用ravenDb时遇到了一个奇怪的问题。我有一个名为"TasksController"的控制器,路径为"api/tasks"。与此相对应,我的ravendb中也有一个任务集合,ID为"tasks/1000"。当您通过http-post创建新任务时,api会按预期创建一个新任务,并重定向到"tasks/{id}"路由。然而,由于新创建的任务的Id是"tasks/1029",返回的重定向URL变成了"../api/tasks/tasks/102九",这显然不存在。有什么建议吗?

代码后方法

    [HttpPost]
    [Route("")]
    public async Task<IHttpActionResult> Post([FromBody]Task task)
    {
        task.Notes.Add(DateTime.Now.ToString("F"));
        await _repositoryFactory.TaskRepository.SaveTask(task);
        await _repositoryFactory.SaveChanges();
        return Redirect(Url.Link("Get", new {id = task.Id}));
    }

获取

    [HttpGet]
    [Route("{id}", Name = "Get")]
    public async Task<IHttpActionResult> Get(string id)
    {
        var task = await _repositoryFactory.TaskRepository.GetById(id);
        return Ok(task);
    }

POSTMAN-发布请求

POST /Hoxro.Web.Api/api/tasks/ HTTP/1.1
Host: localhost
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 86fba9d3-cfcc-4060-226b-1db0eb189c7a
{
  "priority": 1,
  "notes": [
    "02 January 2016 20:52:59"
  ],
  "linkedTasks": [],
  "createdOn": "02/01/2016",
  "assignedTo": "TaskTestUser",
  "matterIds": [],
  "createdBy": "TaskTestUser",
  "completionDate": null,
  "dueDate": null,
  "completed": false
}

结果-

{
  "message": "No HTTP resource was found that matches the request URI 'http://localhost/Hoxro.Web.Api/api/tasks/tasks/1091'.",
  "messageDetail": "No action was found on the controller 'Tasks' that matches the name 'tasks'."
}

正确的结果应该是-http://localhost/Hoxro.Web.Api/api/tasks/1091

我知道这是因为RavenDb Id格式,但如果我不使用标准格式,加载相关文档真的很困难,或者我只是不知道如何加载?

web api url与ravenDb Id格式冲突

如果您想重定向到命名路由,可以使用RedirectToRoute方法,而不是手动生成重定向url。

[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Post([FromBody]Task task)
{
    task.Notes.Add(DateTime.Now.ToString("F"));
    await _repositoryFactory.TaskRepository.SaveTask(task);
    await _repositoryFactory.SaveChanges();
    return RedirectToRoute("Get", new {id = task.Id});
}

同样,"正确的方式"在web api概述中进行了说明,其中url添加到响应标头:

[Route("api/books")]
public HttpResponseMessage Post(Book book)
{
    // Validate and add book to database (not shown)
    var response = Request.CreateResponse(HttpStatusCode.Created);
    // Generate a link to the new book and set the Location header in the response.
    string uri = Url.Link("GetBookById", new { id = book.BookId });
    response.Headers.Location = new Uri(uri);
    return response;
}