【问题标题】:How to implement a .NET WebAPI with a route of "controller?action&parameters"?如何使用“控制器?动作参数”路由实现.NET Web API?
【发布时间】:2020-05-09 23:14:36
【问题描述】:

我正在尝试使用 .NET Standard WebAPI 实现特定的 HTTP 接口(SAP 内容服务器 HTTP 接口),它要求路由全部采用以下形式:

http://server:port/somepath/controller?action&parameter1=value1&parameter2=value2...

例子:

获取

http://www.google.com/myapi/api?getStuff&stuffId=1&otherParameter=2

发布,放置

http://www.google.com/myapi/api?putStuff&stuffId=1&otherParameter=2

是否有可能使用问号之后的操作和之后的参数来执行此特定路由?

接口规范: https://help.sap.com/doc/b743f868cdf249cfb829a5a121cc9436/7.0/en-US/SAPHTTPInterfaceOct.pdf

【问题讨论】:

  • 我会推荐这更 RESTful:GET/PUT/POST/DELETE http://server:port/somepath/{controller}/{id}?{parameter1}={value1}&{parameter2}={value2}...
  • 这能回答你的问题吗? How do I access URL parameters in web API?
  • 您是否有特殊原因希望该操作成为查询参数而不是路径的一部分?虽然您可以更改路由模板来实现此目的,但这是一种非常非标准的模式,会让您的生活更加艰难。
  • 我必须遵守标准协议才能与 SAP ArchiveLink help.sap.com/doc/b743f868cdf249cfb829a5a121cc9436/7.0/en-US/… 集成如果没有,我会以最常用的方式执行此操作,因为我知道这是非常不标准的。
  • 我玩过一个示例项目,但似乎你实际上不能有一个“?”在路线模板中。默认情况下是不允许的。我认为如果您的操作是查询参数,那么您将不得不对 IHttpActionSelector 接口进行某种自定义实现,并编写自己的代码以根据第一个查询参数选择正确的操作。

标签: c# asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:

mapping your routes 应该可以做到这一点:

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}?{action}&{id}&{parameter1}",
    defaults: new { id = RouteParameter.Optional }
);

查询参数可以添加到你的控制器动作中:

public HttpResponseMessage Get(int id, string parameter)
{
   //...
}

【讨论】:

    【解决方案2】:

    我最终在 iis 中使用 url rewrite 模块在到达 api 之前转换请求:

     <rewrite>
        <rules>
          <rule name="convert requests">
            <match url="^api/sapcs" />
            <action type="Rewrite" url="/api/sapcs/{C:1}?{C:2}" appendQueryString="false" />
            <conditions>
              <add input="{QUERY_STRING}" pattern="([^&amp;]+)&amp;(.*)" />
            </conditions>
          </rule>
        </rules>
      </rewrite>
    

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2014-11-07
      • 2018-08-21
      • 2016-02-03
      相关资源
      最近更新 更多