简体   繁体   中英

WebApi Attribute routing not working with [FromUri]

I have a webapi method as shown below

[HttpGet]
[Route("students")]
public string Get([FromUri]Student student)
{
    return "value";
}

and my webapiconfig is

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

When i dont use the [Route("..")] attribute then i get the student object populated and it is null if i use [Route("..")].

Can anyone please help how to solve this.

Thanks

When you use [Route("students")] the following URL will match http://localhost/students?Name=name&Age=12 assuming your Student class has Name and Age properties.

When you don't provide any query parameter it will be null and it's expected behavior.

If you Student object is a struct it will be required parameter, so you will get exception from WebApi, not null

simply, check if its null

[HttpGet]
[Route("students")]
public string Get([FromUri] Student student)
{
    if (student == null)
        student = new Student();
    return "value";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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