简体   繁体   English

ASP.NET Core 2.1 [FromQuery] 未获取参数

[英]ASP.NET Core 2.1 [FromQuery] not getting param

I'm trying to get a param for my WebAPI from a query param using [FromQuery] using ASP.NET Core 2.1.我正在尝试使用 ASP.NET Core 2.1 从使用[FromQuery]的查询参数获取我的 WebAPI 的参数。 For the the life of me I cannot figure out what I'm doing wrong.对于我的生活,我无法弄清楚我做错了什么。

The particular action looks like this:具体操作如下所示:

[Route("api/[controller]/[action]")]
public class AuthController : Controller
{
    [HttpGet]
    [Authorize(Roles = "admin")]
    public async Task<IActionResult> GenerateCode([FromQuery]string email)
    {
        if (String.IsNullOrEmpty(email))
            return new BadRequestObjectResult(new ApiBadRequestResponse(new string[] { "Email is empty." }));

        var result = await _mediator.Send(new CreateAccessCode.Command
        {
            Email = email
        });

        if (result.Succeeded)
            return new OkObjectResult(new ApiOkResponse(result.Data));

        return new BadRequestObjectResult(new ApiBadRequestResponse(result.Errors));
    }
}

email is always null and I've put a breakpoint in the function so I know its getting called. email始终为空,我在函数中放置了一个断点,所以我知道它被调用了。

The request I'm sending is this:我发送的请求是这样的:

{{url}}/api/auth/generatecode?email=test

If I create a new project from scratch, [FromQuery] seems to work, I have no idea what I'm doing differently.如果我从头开始创建一个新项目, [FromQuery]似乎工作,我不知道我在做什么不同。 The action is getting called, but is always return BadResponse due to the first line...正在调用该操作,但由于第一行,它始终返回 BadResponse...

My startup.cs function looks like this:我的 startup.cs 函数如下所示:

services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddMvcOptions(options =>
            {
                options.Filters.Add(new ActionValidationFilter());
            })
            .AddFluentValidation()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();
            })
            .AddSessionStateTempDataProvider();

I'm completely lost.我完全迷失了。 This is the first action I have in my WebAPI that is looking for a query param.这是我在 WebAPI 中寻找查询参数的第一个操作。 All other actions are using FromBody and work fine.所有其他操作都使用 FromBody 并且工作正常。

Option 1)选项1)
Try changing your [HttpGet] attribute to尝试将您的[HttpGet]属性更改为

[HttpGet("GenerateCode/{email}]

You will need to remove /[action] from your controller's Route attribute if doing this, so it'd just be如果这样做,您将需要从控制器的 Route 属性中删除/[action] ,所以它只是

[Route("api/[controller]")]

Option 2)选项 2)
Alternatively, in Startup.cs change app.UseMvc();或者,在Startup.cs更改app.UseMvc(); to

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "api/{controller=Home}/{action=Index}/{id?}");
});

And remove [Route("api/[controller]/[action]")] from the controller attributes and make sure you don't have the [ApiController] attribute either并从控制器属性中删除[Route("api/[controller]/[action]")]并确保您也没有[ApiController]属性

This solution will change your entire project's routing, so you'll have to do the same for all your other API controllers此解决方案将更改您整个项目的路由,因此您必须对所有其他 API 控制器执行相同操作

Option 3)选项 3)
A third solution would be to change [Route("api/[controller]/[action]")] to第三种解决方案是将[Route("api/[controller]/[action]")]更改为

[Route("api/[controller]/[action]/{id?}")]

I have tested all 3 solutions and they all with with the URL {{url}}/api/ControllerName/ActionName?email=test我已经测试了所有 3 个解决方案,它们都使用 URL {{url}}/api/ControllerName/ActionName?email=test

A little late answer but may be helpful for others回答有点晚,但可能对其他人有帮助

Option 4选项 4

You can explicitly name the querystring parameter name within the [FromQuery] attribute您可以在 [FromQuery] 属性中显式命名查询字符串参数名称

[HttpGet]
[Authorize(Roles = "admin")]
public async Task<IActionResult> GenerateCode([FromQuery(Name="email")] string email)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM