在.net核心控制器中使用相同的路由处理GET和POST请求



我正试图用相同的路由在同一个控制器中处理GET和POST,因为我有某些rest调用,数据可能会使用GET或POST来调用相同的端点。。。。

这适用于GET:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpGet("GetAccount")]
[Route("api/accounts/GetAccount")]
public string GetAccount(string accountID)
{
return "echoing accountID: " + accountID;
}
}

这适用于POST:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpPost("GetAccount")]
[Route("api/accounts/GetAccount")]
public string GetAccount([FromForm] string accountID)
{
return "echoing accountID: " + accountID;
}
}

但这不会返回POST的值:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpPost("GetAccount"),HttpGet("GetAccount")]
[Route("api/accounts/GetAccount")]
public string GetAccount(string accountID)
{
// accountID is NULL when doing a POST, but is correct for a GET...
return "echoing accountID: " + accountID;
}
}

在上面的示例中,GET请求可以正常工作,但在执行POST时,参数accountID为NULL,因为我已经删除了[FromForm],以便使其与GET一起工作。

有没有什么方法可以把它组合成一条路线?

这是一个.net core 5.0网站。。。。

我如何从javascript:发布到端点的示例

$.ajax({
url: '/api/accounts/GetAccount',
data: {
accountID: 'abcdefg'
},
type: 'POST',
dataType: 'JSON',
contentType: "application/x-www-form-urlencoded; charset=UTF-8" 
})
.done(function (result) {
// verified that the result is NULL
console.log(result);
})
.fail(function () {
alert("ERROR");;
})
.always(function () {
alert("DONE");
});

这是我完整的启动文件(以防我没有正确注册(:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddHttpContextAccessor();
services.AddRazorPages();
services.AddControllers();
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
}

谢谢!

您可以尝试更改代码,如下所示:

[HttpPost("GetAccount"), HttpGet("GetAccount")]
[Route("api/accounts/GetAccount")]
public string GetAccount()        
{
if ("GET" == HttpContext.Request.Method)
{
//if your `accountID` is fromquery in your get method.
string accountID = HttpContext.Request.Query["accountID"];
return "echoing accountID: " + accountID;
}
else if ("POST" == HttpContext.Request.Method)
{
string accountID = HttpContext.Request.Form["accountID"];
return "echoing accountID: " + accountID;
}
else
{
return "error";
}
}

此外,我认为您的代码可能没有问题。在发布post方法时,您应该检查您的accountID参数。

更新

api控制器的默认属性是[FromBody],因此必须指定源。如果不想指定为[FromForm],可以通过querystring传递数据。

$.ajax({
url: '/api/values/GetAccount?accountID=abcdefg',
type: 'POST',
dataType: 'JSON',
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
})
.done(function (result) {
// verified that the result is NULL
console.log(result.message);
})
.fail(function () {
alert("ERROR");;
})
.always(function () {
alert("DONE");
});
});

行动:

[HttpPost("GetAccount"), HttpGet("GetAccount")]
[Route("api/accounts/GetAccount")]
public IActionResult GetAccount(string accountID)
{
string message = "echoing accountID: " + accountID;
// accountID is NULL when doing a POST, but is correct for a GET...
return new JsonResult(new { message = message });
}

您尝试过创建两个独立的函数吗。一个用于GET,另一个用于POST?您仍然可以将Route属性设置为相同,但将由来自使用者的HTTP方法来确定将调用哪个方法。

此外,您需要使用[FromBody]属性来访问随请求发送的任何有效负载。

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpGet]
[Route("api/accounts/GetAccount")]
public string GetAccount([FromBody] request)
{
return "echoing accountID: " + request.accountID;
}
[HttpPost]
[Route("api/accounts/GetAccount")]
public string CreateAccount([FromBody] request)
{
return "echoing accountID: " + request.accountID;
}
}

编辑

您可能需要将[FromQuery]用于GET端点,将[FromBody]用于POST端点。

然后,对于您的GET,您的URL将使用查询参数而不是数据负载。例如/api/accounts/GetAccount?accountID=12345

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpGet]
[Route("api/accounts/GetAccount")]
public string GetAccount([FromQuery] request)
{
return "echoing accountID: " + request.accountID;
}
[HttpPost]
[Route("api/accounts/GetAccount")]
public string CreateAccount([FromBody] request)
{
return "echoing accountID: " + request.accountID;
}
}

您只是在api/accounts/GetAccount/{accountID}中错过了一个accountID

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpGet]
[HttpPost]
[Route("api/accounts/GetAccount/{accountID}")]
public string GetAccount(string accountID)
{
return "echoing accountID: " + accountID;
}
}

最新更新