[英]WebApi Attribute routing not working with [FromUri]
我有一个 webapi 方法,如下所示
[HttpGet]
[Route("students")]
public string Get([FromUri]Student student)
{
return "value";
}
我的 webapiconfig 是
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
当我不使用 [Route("..")] 属性时,我会填充学生对象,如果我使用 [Route("..")],它为空。
任何人都可以请帮助如何解决这个问题。
谢谢
当您使用[Route("students")]
,假设您的Student
类具有Name
和Age
属性,以下 URL 将匹配http://localhost/students?Name=name&Age=12
。
当您不提供任何查询参数时,它将为 null,这是预期的行为。
如果您的Student
对象是一个struct
,它将是必需的参数,因此您将从 WebApi 获得异常,而不是 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.