FromHeader Asp.NET Core binding to default value

时光怂恿深爱的人放手 提交于 2019-12-12 14:54:46

问题


I'm testing Asp.Net core WebApi with the following basic controller:

[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

Then, in Fiddler, I send the following request:

And, for some reason, the response is 0. Both x and y are binded to the default integer value when entering the method.

I also tried:

[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply([FromHeader]int x, [FromHeader]int y)
    {
        return x * y;
    }
}

But the result is the same. What am I doing wrong?


回答1:


form headers accept string not int so your code should be

[Route("test")]
public class TestController
{
        [Route("mult")]
        [HttpGet]
        public int Multiply([FromHeader]string x, [FromHeader]string y)
        {

            return Int32.Parse(x) * Int32.Parse(y);
        }
}

you have to get values of x and y in string and convert it to int




回答2:


Apparently it was initially thought this wouldn't be needed and they were waiting for feedback. However, it looks like it will likely be in the 2.1.0 milestone according to issue 5859.



来源:https://stackoverflow.com/questions/43816200/fromheader-asp-net-core-binding-to-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!