Skip to content

Commit 1683c8f

Browse files
committed
test(post): response header should contain location of new resource
Issue #21
1 parent b4b1589 commit 1683c8f

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/JsonApiDotNetCore/Controllers/JsonApiController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)
144144

145145
await _entities.CreateAsync(entity);
146146

147-
return Created(HttpContext.Request.Path, entity);
147+
return Created($"{HttpContext.Request.Path}/{entity.Id}", entity);
148148
}
149149

150150
[HttpPatch("{id}")]

test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,5 +68,42 @@ public async Task Request_With_ClientGeneratedId_Returns_403()
6868
// assert
6969
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
7070
}
71+
72+
[Fact]
73+
public async Task PostRequest_ShouldReceiveLocationHeader_InResponse()
74+
{
75+
// arrange
76+
var builder = new WebHostBuilder()
77+
.UseStartup<Startup>();
78+
var httpMethod = new HttpMethod("POST");
79+
var route = "/api/v1/todo-items";
80+
var server = new TestServer(builder);
81+
var client = server.CreateClient();
82+
var request = new HttpRequestMessage(httpMethod, route);
83+
var todoItem = _todoItemFaker.Generate();
84+
var content = new
85+
{
86+
data = new
87+
{
88+
type = "todo-items",
89+
attributes = new
90+
{
91+
description = todoItem.Description,
92+
ordinal = todoItem.Ordinal
93+
}
94+
}
95+
};
96+
request.Content = new StringContent(JsonConvert.SerializeObject(content));
97+
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");
98+
99+
// act
100+
var response = await client.SendAsync(request);
101+
var body = await response.Content.ReadAsStringAsync();
102+
var deserializedBody = (TodoItem)JsonApiDeSerializer.Deserialize(body, _jsonApiContext);
103+
104+
// assert
105+
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
106+
Assert.Equal($"/api/v1/todo-items/{deserializedBody.Id}", response.Headers.Location.ToString());
107+
}
71108
}
72109
}

0 commit comments

Comments
 (0)