我可以在ASP.NET MVC站点中为Web服务(ASMX)路由URL吗?

时间:2009-06-20 03:34:11

标签: c# .net asp.net-mvc httphandler

我已经看到如何使用这样的代码向WebForms添加自定义路由。

public class WebFormsRouteHandler : IRouteHandler
{
    public string VirtualPath { get; set; }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // Compiles ASPX (if needed) and instantiates the web form
        return (IHttpHandler) BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof (IHttpHandler));
    }
}

我正在尝试使用类似的东西,但是对于Web服务文件(TestService.asmx。)之前的方法会引发异常,因为页面不会从IHttpHandler继承。我见过其他一些使用WebServiceHandlerFactory的代码,如下所示

return new WebServiceHandlerFactory().GetHandler(context, requestType, url, pathTranslated);

它返回一个IHttpHandler,就像我需要的那样但它需要传入一个HttpContext,但我作为RequestContext的一部分访问的唯一东西就是一个HttpContextBase。据我所知,我无法从中转换为HttpContext。

有什么想法吗?或者可能采取不同的方式去做吧?我想要完成的是通过正常的路由系统控制我的Web服务的URL。一个例子是希望TestService.asmx作为ExampleTestService /.

出现

2 个答案:

答案 0 :(得分:1)

有趣的想法。我不知道你可以这样使用网络表单。我们目前正在将旧的网络表单应用与IgnoreRoutes集成。我肯定会给你的问题加书签;)

但也许我可以帮助你解决问题。好的旧HttpContext仍然存在,它只是由MVC包装到模拟友好HttpContextBase中。

您可以使用

检索原始HttpContext
var context = System.Web.HttpContext.Current;

在控制器中,您必须完全指定类型,以区别于名为HttpContext的控制器属性

答案 1 :(得分:1)

我就是这样做的:

 Return New WebServiceHandlerFactory().GetHandler(HttpContext.Current, "*", "/Build/WebService.asmx", HttpContext.Current.Server.MapPath(aspxToLoad))