Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I route a url for a web service (ASMX) in an ASP.NET MVC Site?

I have seen how you can add custom routes to WebForms by using some code like this.

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));
    }
}

I'm trying to get a similar thing to work but for web service files (TestService.asmx.) That previous method throws an exception because the page does not inherit from IHttpHandler. I've seen some other code that uses the WebServiceHandlerFactory like this

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

That returns an IHttpHandler like I need but it needs an HttpContext passed in but the only thing I have access too as part of RequestContext is an HttpContextBase. From what I can tell I can't convert to an HttpContext from that.

Any ideas? Or maybe a different way to go about it? What I'm trying to accomplish is to control the urls for my web services through the normal routing system. An example is wanting TestService.asmx to come up as ExampleTestService/.

like image 952
Nathan Palmer Avatar asked Nov 06 '22 20:11

Nathan Palmer


2 Answers

Interesting idea. I didn't know you could use web forms that way. We are currently integrating old web form apps with IgnoreRoutes. I'll definitely bookmark your question ;)

But maybe I can help you with your problem. The good old HttpContext still exists, it's just wrapped by MVC into the mock friendly HttpContextBase.

You can retrieve the original HttpContext with

var context = System.Web.HttpContext.Current;

In a controller you have to specify the type fully to distinguish it from the controller property called HttpContext

like image 54
chris166 Avatar answered Nov 14 '22 21:11

chris166


This is how I do it:

 Return New WebServiceHandlerFactory().GetHandler(HttpContext.Current, "*", "/Build/WebService.asmx", HttpContext.Current.Server.MapPath(aspxToLoad))
like image 36
Markive Avatar answered Nov 14 '22 23:11

Markive