如何处理 GET 操作的 Web API 查询字符串中的特殊字符“*”

How to handle special character '*' in webapi querystring for GET Operation

我们正在尝试处理查询字符串中的“*”(星号)以进行搜索操作,但出现以下错误。我们尝试在 webconfig 中使用 requesstPathInvalidChacters 并在 Routes 中使用 [FromUri],但没有成功。 呼叫甚至没有到达控制器块

sample request Url: http://localhost:8080/test/search/ABCD*12*234

   <httpRuntime targetFramework="4.5.2" maxRequestLength="2097152" requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?,*" />

Exception:

<!DOCTYPE html>
<html>
    <head>
        <title>A potentially dangerous Request.Path value was detected from the client (*).</title>
        <meta name="viewport" content="width=device-width" />

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>A potentially dangerous Request.Path value was detected from the client (*).</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (*).<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (*).]
   System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +9859608
   System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +53
</pre></code>

我刚刚在 ASP .NET Core 2.0 Web API 项目中尝试过,它对我没有任何问题。但请参阅 this 以获取可能的修复方法。

以下代码在 .Net Core 2 中对我有效:

[Route("test/search/{id}")]
[HttpGet()]
public string Test(string id)
{
    return id;
}

URL: http://localhost:56403/api/values/test/search/ABCD*12*234

结果:ABCD*12*234