Bastien Vandamme
Bastien Vandamme

Reputation: 18465

Why urlHelper.Link method return null or result in exception?

Could you help me to understand and fix the reason why my urlHelper.Link method return null?

I give you my 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.
    }

What is the correct way to use UrlHelper to get my link or route?

Upvotes: 0

Views: 437

Answers (1)

Bastien Vandamme
Bastien Vandamme

Reputation: 18465

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.
}

Upvotes: 1

Related Questions