加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – asp.net mvc:如何模拟Url.Content(“?”)?

发布时间:2020-12-16 07:26:40 所属栏目:asp.Net 来源:网络整理
导读:有谁知道如何模拟Url.Content(“?”)? (顺便说一句:我正在使用Moq) 解决方法 你指的是控制器中的Url属性,我认为它属于UrlHelper类型.我们能够模拟这个的唯一方法是提取IUrlHelper接口,并创建一个UrlHelperWrapper类,它同时实现它并包装本机UrlHelper类型.
有谁知道如何模拟Url.Content(“?”)?

(顺便说一句:我正在使用Moq)

解决方法

你指的是控制器中的Url属性,我认为它属于UrlHelper类型.我们能够模拟这个的唯一方法是提取IUrlHelper接口,并创建一个UrlHelperWrapper类,它同时实现它并包装本机UrlHelper类型.然后我们在BaseController上定义一个新属性,如下所示:

public new IUrlHelper Url
{
    get { return _urlHelper; }
    set { _urlHelper = value; }
}

这允许我们创建IUrlHelper的模拟并注入它们,但在默认情况下使用我们的UrlHelperWrapper类的实例.对不起,它啰嗦了,但正如你所发现的那样,这是一个问题.但是,它确实无需更改控制器中的任何Url.Action和类似的调用.

这是界面:

public interface IUrlHelper
{
    string Action(string actionName);
    string Action(string actionName,object routeValues);
    string Action(string actionName,string controllerName);
    string Action(string actionName,RouteValueDictionary routeValues);
    string Action(string actionName,string controllerName,object routeValues,string protocol);
    string Action(string actionName,RouteValueDictionary routeValues,string protocol,string hostName);
    string Content(string contentPath);
    string Encode(string url);
    string RouteUrl(object routeValues);
    string RouteUrl(string routeName);
    string RouteUrl(RouteValueDictionary routeValues);
    string RouteUrl(string routeName,object routeValues);
    string RouteUrl(string routeName,RouteValueDictionary routeValues);
    string RouteUrl(string routeName,string protocol);
    string RouteUrl(string routeName,string hostName);
}

我不打算给你UrlHelperWrapper的定义 – 它实际上只是一个实现这个的愚蠢的包装器,并将所有调用传递给UrlHelper.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读