c# - MVC Web API 2 中的点字符 '.' 用于 api/people/STAFF.45287 等请求

标签 c# asp.net-mvc-4 asp.net-web-api asp.net-mvc-routing asp.net-web-api2

我尝试使用的 URL 格式如下:http://somedomain.com/api/people/staff.33311 (就像 LAST.FM 这样的网站允许在其 RESTFul 和网页 url 中使用各种符号,例如“http://www.last.fm/artist/psy'aviah”是 LAST.FM 的有效 url)。

以下场景有效: - http://somedomain.com/api/people/ - 返回所有人 - http://somedomain.com/api/people/staff33311 - 也可以,但这不是我想要的 我希望 url 接受一个“点”,如下例 - http://somedomain.com/api/people/staff.33311 - 但这给了我一个

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

我设置了以下内容:

  1. Controller “PeopleController”

    public IEnumerable<Person> GetAllPeople()
    {
        return _people;
    }
    
    public IHttpActionResult GetPerson(string id)
    {
        var person = _people.FirstOrDefault(p => p.Id.ToLower().Equals(id.ToLower()));
        if (person == null)
            return NotFound();
    
        return Ok(person);
    }    
    
  2. WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
    
        // Web API routes
        config.MapHttpAttributeRoutes();
    
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    

我已经尝试遵循这篇博文的所有提示 http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx但它仍然行不通。我也认为这很乏味,我想知道是否有另一种更好、更安全的方法。

我们的 Id 内部是这样的,所以我们将不得不找到一种解决方案来以某种方式适合点,最好是“.”的样式。但如果需要的话,我愿意接受其他关于 url 的建议......

最佳答案

用斜杠作为 URL 的后缀,例如http://somedomain.com/api/people/staff.33311/而不是 http://somedomain.com/api/people/staff.33311 .

关于c# - MVC Web API 2 中的点字符 '.' 用于 api/people/STAFF.45287 等请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998816/

相关文章:

c# - Newsoft Json 反序列化为产品集合不起作用

c# - 使用 xmlns 属性( namespace )查询 XDocument

c# - 如何避免 split ?

javascript - 无法从@Url.Action 访问变量

c# - 如何在 MVC 4 中为枚举创建默认编辑器模板?

c# - Web Api FromBody 来自网络客户端为空

c# - 逆变似乎会导致冲突的行为

c# - 生成具有角色的身份用户(从 Web API 到 MVC 应用程序)

asp.net-web-api - Swashbuckle、多个 API 版本和虚拟目录

c# - WebApi 2 中 IHostBufferPolicySelector 上下文中的空 RouteData