使用"/"将数据从Angular传递到.Net Core Web Api.特点

编程入门 行业动态 更新时间:2024-10-21 16:39:09
本文介绍了使用"/"将数据从Angular传递到.Net Core Web Api.特点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

不休息的日子"

由于在这种情况下,我对webapi的请求如下所示:

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

那个角色/破坏了请求.如何正确地将其传递给WebApi?昨天我很着急,在Angular端进行了编码,在Web Api端进行了解码,但是它不起作用,所以我决定将其还原.

昨天尝试,角度应用程序:

[...]公共getResstringByPhrase(来源:字串):可观察的< string>{const result = this.http.get(this.url +"getResstring/" +来源,{responseType:'text'})返回结果}[...]

Core Web API:

[HttpGet("{* phrase}'))][Route("getResstring/{phrase}"))]公共IActionResult Get(字符串短语){var resstring = _translationRepository.GetResstringByPhrase(短语);返回新的OkObjectResult(resstring);}

Startup.cs(仅配置):

public void Configure(IApplicationBuilder应用程序,IWebHostEnvironment env){如果(env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});

}}

但是即使进行了这种尝试,它也不适用于带有"/"字样的短语.符号

#UPDATE

冲突的行为:

[HttpGet(" {languageCharset}/{resstring}"))][Route("{languageCharset}/{resstring}"))]公共IActionResult Get(字符串resstring,LanguageCharset languageCharset){var translation = _translationRepository.GetTranslatedByResstring(resstring,languageCharset);返回新的OkObjectResult(translate);}

#UPDATE 2:

我成功了,现在"/"可以,但是我对"+"有疑问.代码

Webapi:

[HttpGet("{phrase}'))][Route("getResstring/{phrase}"))]公共IActionResult Get(字符串短语){短语= HttpUtility.UrlDecode(短语);var resstring = _translationRepository.GetResstringByPhrase(短语);返回新的OkObjectResult(resstring);}

Angular应用:

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

现在错误是(仅当短语的内部带有"+"时出现):

HTTP错误404.11-未找到

请求过滤模块被配置为拒绝替代双重解决方案的取消的拒绝.(对不起,我用我的语言翻译)

解决方案

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

例如:

[Route("api/[controller]"))][ApiController]公共类LanguagesController:控制器{[Route("getResstring/{* phrase}"))]公共字符串GetResstringByPhrase(字符串短语){返回"aa";}}

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

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

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

结果(为进行测试,我只使用浏览器发送请求.浏览器将自动对URL进行编码):

参考:

更新2

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

请查看以下帖子:

注意:

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

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

2.在搜索栏中搜索 config ->选择 Web配置文件:

I have issue with passing data from angular to webapi. I need to translate some phrases from my DB and everything works until my phrase looks like this:

"day w/o break"

Because in this situation my request to webapi looks like:

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

And that character / destroying the request. How to pass it to WebApi correctly? I did it in hurry yesterday do encode on Angular side and decode on Web Api side but it not works, so i decided to revert it.

Yesterday attempt, angular app:

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

Core web api:

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

Startup.cs (only Configure):

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

} }

But even with this attempt, it doesn't work with phrases with "/" symbol

#UPDATE

Conflicting action:

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

#UPDATE 2:

I made it, now "/" works, but i have problems with "+". Code

Webapi:

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

Angular app:

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

And now the error is (only appears when phrase have "+" inside):

HTTP Error 404.11 - Not Found

The request filtering module is configured to reject the rejection of the cancellation of an alternate double solution. (sorry for translation from my language)

解决方案

You could use asterisk * or double asterisk ** as a prefix to a route parameter:

For example:

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

You could send request url like:localhost:44973/api/languages/getResstring/day%20w/o%20break

Be sure your Startup.cs should be like below:

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

Result(For test,I just use browser to send request.The browser will encode the url automatically):

Reference:

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

Update:

Your code has a mistake.Model could not be passed as route value.It could be passed from query string or from body.So you can't use [Route("{languageCharset}/{resstring}")] to pass the model data to the action.

Then,you need use the specific attribute(e.g [FromQuery],[FromBody],[FromRoute]) to specify the parameter source from.

The difference between route and query string is that:localhost:44973/api/languages/getResstring?Id=1,getResstring is route value.?Id=1 is query string.

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

Result:

Update 2

For cannot use plus symbol in route,this is an IIS issue:

Please look at the following post:

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

You need add the following section in your web.config:

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

Result:

Note:

If you do not have web.config file in your project,you could follow the steps to create it:

1.Right-click your project->choose Add->choose New Item:

2.Search config in search bar->choose Web Configuration File:

更多推荐

使用"/"将数据从Angular传递到.Net Core Web Api.特点

本文发布于:2023-11-15 10:28:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Angular   quot   Net   Api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!