asp.net-mvc – Url.Action with RouteValueDictionary with Protocol

一直在看这个一段时间,感觉就像我只是笨蛋想要更多的眼睛.

我需要生成一个完整的URL(例如http://www.domain.com/controller/action?a=1\u0026amp;b=2),一般来说,我只需使用Url.Action就可以通过指定协议来完成此任务:

var url = Url.Action("Action","Controller",new { a = 1,b = 2 },"http");

我已经开始组合一个返回RouteValueDictionary的类,以使这些匿名对象消失.但是,我不能让它与帮手一起工作.

var x = Url.Action("Action",new RouteValueDictionary(new { a = 1,b = 2 }),"http");
// "http://127.0.0.1/Controller/Action?Count=2&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D",var y = Url.Action("Action","http");
// "http://127.0.0.1/Controller/Action?a=1&b=2"

任何指向一个facepalm的指针非常感谢:)

更新:

最好澄清一点,在上面的例子中,我需要让’X’变量工作正常,因为RouteValueDictionary是在代码的其他地方创建的.假设RouteValueDictionary是正确的.

我只是不明白为什么这个工作与匿名对象,但是包装在同一个对象中的同一个对象包裹在一个RouteValueDictionary中,使得帮助者变得怪异了.

解决方法

您正在使用的重载期望为您传递RouteValueDictionary的参数键入“object”.由于某种原因,这是导致问题,可能与.ToString()有关?使用一个接受RouteValueDictionary的重载,这应该工作.

要测试这个,添加一个hostName参数来选择如下所示的重载:

编辑

您可以在项目中使用此扩展,将您需要的重载添加到Url.Action.在内部,它将从请求中解析并添加hostName.

public static string Action
    (this UrlHelper helper,string action,string controller,RouteValueDictionary routeValues,string protocol)
{
     string hostName = helper.RequestContext.HttpContext.Request.Url.Host;
     return helper.Action(action,controller,routeValues,protocol,hostName);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....