【问题标题】:.Net Web Api Get Method.Net Web Api 获取方法
【发布时间】:2018-09-11 13:32:01
【问题描述】:

我正在学习 .NET Web Api。

所以这是默认的 GET 方法

// GET: api/UserProfiles/5
[ResponseType(typeof(UserProfile))]
public IHttpActionResult GetUserProfile(int id)
{
    UserProfile userProfile = db.UserProfiles.Find(id);
    if (userProfile == null)
    {
        return NotFound();
    }

    return Ok(userProfile);
}

这是我的模型:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Phone { get; set; }
}

如何让它通过Name 而不是ID 进行搜索。 据我了解,我需要将GetUserProfile(int id) 更改为GetUserProfile(string name) 并在WebApiConfig.cs 中更改为

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

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

但它不起作用。有什么建议吗?

【问题讨论】:

  • 什么是不工作的?你怎么知道?服务器是否抛出错误?
  • 您确定要更改默认路由吗?你考虑过attribute routing吗?

标签: c# .net asp.net-web-api get


【解决方案1】:

不,你不应该改变路线。只需您仍然使用GetUserProfile(string name),请求将是/api/UserProfiles?name=...

【讨论】:

  • 但是如果 OP 想改变路线怎么办?:它应该也可以。不要误会我的意思;我认为将 OP 指向替代方案是件好事,但它仍然不是原始问题的答案。这对于其他用例可能很重要。
  • 这也没有回答问题,因为它使用查询语法,而不是路由参数语法。它应该像/api/UserProfiles/{name} 一样工作。
  • 谢谢,我明白了。实际上/api/UserProfiles/{name} 在这种情况下效果很好
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 2018-12-29
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 2012-10-24
相关资源
最近更新 更多