您能帮助我理解并解决urlHelper.Link方法返回null的原因吗?
我给你我的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获取链接或路由的正确方法是什么?
答案 0 :(得分:0)
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.
}