[英]WebApi Attribute routing not working with [FromUri]
I have a webapi method as shown below我有一个 webapi 方法,如下所示
[HttpGet]
[Route("students")]
public string Get([FromUri]Student student)
{
return "value";
}
and my webapiconfig is我的 webapiconfig 是
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("..")].当我不使用 [Route("..")] 属性时,我会填充学生对象,如果我使用 [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.当您使用
[Route("students")]
,假设您的Student
类具有Name
和Age
属性,以下 URL 将匹配http://localhost/students?Name=name&Age=12
。
When you don't provide any query parameter it will be null and it's expected behavior.当您不提供任何查询参数时,它将为 null,这是预期的行为。
If you Student
object is a struct
it will be required parameter, so you will get exception from WebApi, not null如果您的
Student
对象是一个struct
,它将是必需的参数,因此您将从 WebApi 获得异常,而不是 null
simply, check if its null简单地,检查它是否为空
[HttpGet]
[Route("students")]
public string Get([FromUri] Student student)
{
if (student == null)
student = new Student();
return "value";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.