代码之家  ›  专栏  ›  技术社区  ›  Bastien Vandamme

为什么urlhelper.link方法返回空值或导致异常?

  •  0
  • Bastien Vandamme  · 技术社区  · 7 年前

    你能帮我理解并修正我的urlhelper.link方法返回空值的原因吗?

    我给你我的API

        [Route("api/Document", Name = "CreateDocument")]
        public IHttpActionResult Post(Document document)
        {
            …
        }
    
        [Route("api/Document/{documentId}", Name = "DeleteDocument")]
        public IHttpActionResult Delete(Guid documentId)
        {
            …
        }
    
        public string RunThis(HttpRequestMessage request, Guid Id)
        {
            var urlHelper = new UrlHelper(request);
    
            urlHelper.Link("CreateDocument", null);
            // In immediate window: "http://localhost:55328/api/Document"
            // Good
    
            urlHelper.Link("DeleteDocument", Guid.NewGuid())
            // In immediate window: null
            // Why? 
    
            urlHelper.Link("DeleteDocument", new { Guid.NewGuid() })
            // In immediate window: error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
    
            urlHelper.Link("DeleteDocument", new { documentId = Guid.NewGuid() })
            // In immediate window: The expression cannot be evaluated.  A common cause of this error is attempting to pass a lambda into a delegate.
        }
    

    使用urlhelper获取链接或路线的正确方法是什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Bastien Vandamme    7 年前
    public string RunThis(HttpRequestMessage request, Guid Id)
    {
        var urlHelper = new UrlHelper(request);
    
        var parameters = new Dictionary<string, object>
                        {
                            { "documentId", Id }
                        };
    
        urlHelper.Link("DeleteDocument", parameters)
        // In immediate window: "http://localhost:55328/api/Document/373c13da-aeb7-41f8-af66-ca78a06f7964"
        // Finally. The solution is to create a dictionary.
    }
    
    推荐文章