使用“/”字符将数据从 Angular 传递到 .Net Core Web Api

Pass data from Angular to .Net Core Web Api with "/" character

我在将数据从 angular 传递到网络 api 时遇到问题。 我需要从我的数据库中翻译一些短语,一切正常,直到我的短语看起来像这样:

"day w/o break"

因为在这种情况下我对 webapi 的请求看起来像:

https://localhost:44973/api/translation/getResstring/day%20w/o%20break

还有那个角色/破坏请求。 如何正确传递给WebApi?我昨天匆忙做了它在 Angular 端编码并在 Web Api 端解码但是它不起作用,所以我决定恢复它。

昨天尝试,angular 应用:

[...]
public getResstringByPhrase(
source: string
): Observable<string> {
  const result = this.http.get(this.url + "getResstring/" + source, { responseType: 'text' })
  return result
}
[...]

.net 核心网 api:

[HttpGet("{*phrase}")]
[Route("getResstring/{phrase}")]
public IActionResult Get(string phrase)
{
  var resstring = _translationRepository.GetResstringByPhrase(phrase);
  return new OkObjectResult(resstring);
}

Startup.cs(仅配置):

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseHttpsRedirection();

  app.UseRouting();

  app.UseAuthorization();

  app.UseEndpoints(endpoints =>
  {
    endpoints.MapControllers();
  });

} }

但即使进行了这种尝试,它也不适用于带有“/”符号的短语

#更新

冲突操作:

   [HttpGet("{languageCharset}/{resstring}")]
    [Route("{languageCharset}/{resstring}")]
    public IActionResult Get(string resstring, LanguageCharset languageCharset)
    {
      var translate = _translationRepository.GetTranslatedByResstring(resstring, languageCharset);
      return new OkObjectResult(translate);
    }

#更新 2:

我做到了,现在“/”有效,但“+”有问题。代码

网络api:

[HttpGet("{phrase}")]
    [Route("getResstring/{phrase}")]
    public IActionResult Get(string phrase)
    {
      phrase = HttpUtility.UrlDecode(phrase);
      var resstring = _translationRepository.GetResstringByPhrase(phrase);
      return new OkObjectResult(resstring);
    }

Angular 应用程序:

if( translatedElements[index].getIsTranslated() === false ) {
          this.getResstringByPhrase(encodeURIComponent(translatedElements[index].getValue())).subscribe(async res => {
            const translatedLabel = await this.GetTranslatedByResstring(res, 1045).toPromise()
            if (translatedLabel.getPhrase() !== '') {
              translatedElements[index].setValue(translatedLabel.getPhrase())
            }   
          })
        }

现在的错误是(只有当短语里面有“+”时才会出现):

HTTP 错误 404.11 - 未找到

请求过滤模块配置为拒绝取消备选双解。 (抱歉翻译我的语言)

您可以使用星号 * 或双星号 ** 作为路由参数的前缀:

例如:

[Route("api/[controller]")]
[ApiController]
public class LanguagesController : Controller
{
    [Route("getResstring/{*phrase}")]
    public string GetResstringByPhrase(string phrase)
    {
        return "aa";
    }

}

您可以发送请求 url 例如:https://localhost:44973/api/languages/getResstring/day%20w/o%20break

请确保您的 Startup.cs 应该如下所示:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

结果(为了测试,我只是用浏览器发送 request.The 浏览器会自动编码 url):

参考:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#route-template-reference

更新:

您的代码有一个 mistake.Model 无法传递,因为路由 value.It 可以从查询字符串或 body.So 传递,您不能使用 [Route("{languageCharset}/{resstring}")] 传递动作的模型数据。

然后,您需要使用特定的属性(例如[FromQuery][FromBody][FromRoute])来指定参数来源。

路由和查询字符串的区别在于:https://localhost:44973/api/languages/getResstring?Id=1getResstring是路由值。?Id=1是查询字符串。

[Route("api/[controller]")]
[ApiController]
public class LanguagesController : Controller
{
    [Route("getResstring/{*phrase}")]
    public string GetResstringByPhrase(string phrase)
    {
        return "aa";
    }
    [HttpGet]
    [Route("{resstring}")]
    public IActionResult Get([FromRoute]string resstring,[FromQuery]LanguageCharset languageCharset)
    {
        return Ok();
    }
}

结果:

更新 2

无法在路由中使用加号,这是 IIS 问题:

请看下面post:

double escape sequence inside a url : The request filtering module is configured to deny a request that contains a double escape sequence

您需要在 web.config 中添加以下部分:

<?xml version="1.0" encoding="utf-8"?>
<configuration> 
  <system.webServer>
    <security>
      <requestFiltering allowDoubleEscaping="true" />
    </security>
  </system.webServer>
</configuration>

结果:

注:

如果您在您的项目中没有web.config文件,您可以按照以下步骤创建它:

1.Right-单击您的项目->选择Add->选择New Item:

2.Search config 在搜索栏中->选择 Web Configuration File:

如果我输入:https://localhost:44397/api/translation/getResstring/polish

然后我收到:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|cfc7e08b-41bcf96eadd38d17.","errors":{"languageCharset":["The value 'getResstring' is not valid."]}}

如果我输入:https://localhost:44397/api/translation/getResstring/day%20w/o%20break

然后我收到:找不到页面

当我删除所有 * 时,第一次尝试工作,第二次给出相同的结果