如果我理解正确的话,在 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 });
}
}
我可以使用我认为资源的规范 URLGET
资源:
$ 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 段。
如何使生成的网址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 });
}