【问题标题】:ASMX service in a ASP.NET WEB API projectASP.NET WEB API 项目中的 ASMX 服务
【发布时间】:2018-06-17 21:14:51
【问题描述】:

使用我们的 Web API 站点的应用程序之一只能使用 ASMX Web 服务。我最近将带有 Web 服务的 Web API 项目部署到开发服务器,并尝试使用自动生成的网页测试 Web 服务。

我在system.web -> webService -> protocols web.config 部分启用了HttpGet 和HttpPost,以便使用自动生成的网页进行测试。浏览到我要测试的方法时,URL格式如下:

https://mydomain.dev.com/MyApp/MyService.asmx?op=MyMethod

当我单击调用按钮时,我收到以下消息:

没有这样的主机是已知的

响应中的 URL 格式如下:

https://mydomain.dev.com/MyApp/MyService.asmx/MyMethod

如何配置路由以允许我在启用HttpGet 和HttpPost 协议的情况下使用自动生成的ASMX 页面进行测试?

【问题讨论】:

  • 路由很可能被web api路由拦截和处理。展示您如何设置路由,以便我们弄清楚如何添加允许正确映射 asmx 的路由
  • 目前在WebApiConfig的Register方法中有DefaultApiMapHttpRoute
  • 我更新了答案

标签: c# web-services asp.net-web-api asp.net-mvc-routing asmx


【解决方案1】:

为了使用 ASMX Web 服务自动化测试工具,我必须创建一个自定义路由处理程序,该处理程序实现 IRouteHander 接口以将 HTTP POST 映射到适当的 Web 服务。自定义 IRouteHandler 将为 Web 服务返回正确的 IHttpHandler。

WebServiceRouteHandler 路由处理程序

public class WebServiceRouteHandler : IRouteHandler
{
    private readonly string _virtualPath;
    private readonly WebServiceHandlerFactory _webServiceHandlerFactory = new WebServiceHandlerFactory();

    public WebServiceRouteHandler(string virtualPath)
    {
        if (virtualPath == null) throw new ArgumentNullException("virtualPath");

        if (!virtualPath.StartsWith("~/")) throw new ArgumentException("Virtual path must start with ~/", "virtualPath");

         _virtualPath = virtualPath;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        //Note: can't pass requestContext.HttpContext as the first parameter because that's type HttpContextBase, while GetHandler wants HttpContext.
        return _webServiceHandlerFactory.GetHandler(HttpContext.Current, requestContext.HttpContext.Request.HttpMethod, _virtualPath, requestContext.HttpContext.Server.MapPath(_virtualPath));
     }
}

RouteConfig.cs 中的RegisterRoutes 方法

routes.Add("MyWebServiceRoute", new Route(
            "path/to/service/method",
            new RouteValueDictionary() { { "controller", null }, { "action", null } }, new WebServiceRouteHandler("~/MyWebService.asmx")));

我的实现基于以下博文:Creating a route for an .asmx Web Services with ASP.NET Routing

【讨论】:

    【解决方案2】:

    我不确定,但我认为您需要在 web.config 中为 Web 服务启用 HttpGet 和 HttpPost 协议。可以参考this documentation:

      <system.web>
        <webServices>
          <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
          </protocols>
        </webServices>
      <system.web>
    

    更新

    您必须确保有一个 httpHandler for asmx files 并且它没有被 web api 的 httpHandler 覆盖。然后确保你的 webapi 路由器没有映射路由,例如:

    routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");
    

    See this question

    【讨论】:

    • 我的 web.config 中确实启用了这些协议。问题是从自动生成的测试页面发布时,我得到“没有这样的主机是已知的”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多