当前位置: 移动技术网 > IT编程>开发语言>.net > 【寻求解决方法】ASP.NET Core WebAPI 遇到的坑:API访问被阻塞

【寻求解决方法】ASP.NET Core WebAPI 遇到的坑:API访问被阻塞

2018年02月02日  | 移动技术网IT编程  | 我要评论

北京pm2.5,花开杏林txt,华美a100

 

假设现在有三个项目,ProjectA,ProjectB,ProjectC。

ProjectA项目中有俩个接口,Get(),GetTest( string code )。

ProjectB项目中一个接口,GetHelloWorld()。

ProjectC是一个后台任务。

 

遇到的问题是:

ProjectA 项目的 Get接口 访问 ProjectB 项目的 HelloWorld,此时 PojectC 项目请求 ProjectA 中的 GetTest, 这时问题就出现了,ProjectA 项目中的 GET  请求被阻塞必须等到 PojectC 的访问结束 ProjectA 访问才能继续执行

我写了一个demo

ProjectA代码:

[HttpGet]
        public async Task<IEnumerable<string>> Get() {
            while ( true ) {
                try {
                    Trace.WriteLine( $"{DateTime.Now} start web request" );
                    var apiUrl = $"http://localhost:2615/";
                    var res = await GetAsync( apiUrl );
                    Trace.WriteLine( $"{DateTime.Now} end web request" );
                }
                catch {
                }
            }
        }

        [HttpGet( "{id}" )]
        public string Gettest( string code ) {
            return code;
        }

 

ProjectB项目代码:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                Trace.WriteLine(DateTime.Now.ToString());
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

ProjectC项目代码:

int threadCount = 100;
            Semaphore semaphore = new Semaphore( 0, 1000 );
            for ( int i = 0; i < threadCount; i++ ) {
                new Thread( threadId =>
                 {
                     for ( int j = 0; j < 100; j++ ) {
                         try {
                             using ( var client = new WebClient { Proxy = null } ) {
                                 Console.WriteLine( "thread{0}round{1}->{2}", threadId, j, client.DownloadString( $"http://localhost:40895/api/values/Gettest?code={Guid.NewGuid()}" ) );
                             }
                         }
                         catch ( Exception err ) {
                             Console.WriteLine( "thread{0}round{1}->error", threadId, j );
                         }
                     }
                     semaphore.Release();
                 } ).Start( i );
            }

 

不知道这时微软的Bug还是我自己使用的问题,所以还请请各位博友帮忙看看这是什么问题…

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网