私が物事を正しく理解していれば、ASP.NET Core 3では、エンドポイントルーティングを使用することになっています。そのため、私は次のStartup
ようなクラスを作成しました。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
次のようなPost
とGet
メソッドを使用してRESTリソースを作成したいと思います。
[ApiController, Route("[controller]")]
public class FooController
{
[HttpPost]
public ActionResult Post(Foo foo)
{
return new CreatedAtRouteResult(new { id = foo.Id }, foo);
}
[HttpGet("{id}")]
public ActionResult Get(string id)
{
return new OkObjectResult(new Foo { Id = id });
}
}
GET
リソースの正規URLと見なすものを使用してリソースを作成できます。
$ curl -v http://localhost:52268/foo/bar
* Trying ::1:52268...
* TCP_NODELAY set
* Connected to localhost (::1) port 52268 (#0)
> GET /foo/bar HTTP/1.1
> Host: localhost:52268
> User-Agent: curl/7.67.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Content-Type: application/json; charset=utf-8
< Server: Microsoft-IIS/10.0
< X-Powered-By: ASP.NET
< Date: Tue, 12 May 2020 15:25:12 GMT
<
{"id":"bar"}* Connection #0 to host localhost left intact
かっこいい、それはうまくいく。POST
表現を試してみましょう:
$ curl -v http://localhost:52268/foo -H "Content-Type: application/json" -d "{ \"id\": \"bar\" }"
* Trying ::1:52268...
* TCP_NODELAY set
* Connected to localhost (::1) port 52268 (#0)
> POST /foo HTTP/1.1
> Host: localhost:52268
> User-Agent: curl/7.67.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 15
>
* upload completely sent off: 15 out of 15 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 201 Created
< Transfer-Encoding: chunked
< Content-Type: application/json; charset=utf-8
< Location: http://localhost:52268/Foo?id=bar
< Server: Microsoft-IIS/10.0
< X-Powered-By: ASP.NET
< Date: Tue, 12 May 2020 15:25:53 GMT
<
{"id":"bar"}* Connection #0 to host localhost left intact
Location
ヘッダーに注目してください。それはhttp://localhost:52268/Foo?id=bar
、ではありませんhttp://localhost:52268/foo/bar
。id
クエリ文字列パラメータではなく、URLセグメントとしてフォーマットされます。
生成されたURLを作成するにはどうすればよいhttp://localhost:52268/foo/bar
ですか?
(ケーシングの問題は無視してください。その方法を教えていただければhttp://localhost:52268/Foo/bar
、答えとしてカウントされます。)
を使用できますCreatedAtAction
。これは、コントローラークラスがController
またはから派生している場合に使用できますControllerBase
。
return CreatedAtAction(nameof(Get), new { foo.Id }, foo);
または次のような名前付きルートを試してください
return new CreatedAtRouteResult(nameof(Get), new { id = foo.Id }, foo);
次に、の属性をGet
に変更します
[HttpGet("{id}", Name = nameof(Get))]
public ActionResult Get(string id)
{
return new OkObjectResult(new Foo { Id = id });
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加