ASP.Net Core 2.2 在 Linux 上通过 NGINX 部署,POST 请求返回 HTTP 错误 400。

huangapple go评论79阅读模式
英文:

ASP.Net Core 2.2 deployed on Linux via NGINX, POST requests returning HTTP Error 400

问题

I am deploying a simple asp.net core app that uses only the home controller and a single post method. We have two internal networks, one consisting of only Windows machines and the other consisting of only Linux machines. The asp core app has been deployed via NGINX on the Linux side. To clarify, I can view the website from the Windows side through the Linux Login node's IP Address 10.10.40.50:8081 as the URL. To view the website from the Linux side on the machine hosting the site, it is just localhost:5000.

The post method simply takes a single input and returns a corresponding PDF file to the input, and is as follows:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(string label) {
    if (ModelState.IsValid && label.Length > 0) {
        string newLabel = label.Trim().Split(' ')[0].ToUpper();
        if (fstickChecker.Contains(newLabel)) {
            var pdf = await CreatePDF(newLabel);
            return pdf;
        } else {
            return RedirectToAction("Index", new RouteValueDictionary(new { action = "Index", err = "Invalid label selected" }));
        }
    }
    return View();
}

The Razor code:

<form method="post" action="/Home/Create">
    @Html.AntiForgeryToken()
    <input size="60" type="text" name="label" class="form-control" id="labeler" placeholder="Enter Label" style="float:left;">
    <div class="rotator-buttons" style="padding-top:45px;">
        <button type="submit" class=" btn btn-01 t-white" style="float:left; height:40px;width:140px;background-color:#706552">Create PDF</button>
    </div>
</form>

The post method operates correctly when run on a Windows machine via the VS 2017 debugger and from the Linux machine hosting it (i.e., when using the localhost:5000 address).

However, it fails when viewing the site from the Windows side (i.e., the 10.10.40:8081).

There is a GET method (named Search) that provides Search Engine type functionality in the textbox where the label is entered that operates correctly under all circumstances, so it appears that only the POST method is failing for whatever reason.

My Program.cs portion:

public class Program {
    public static void Main(string[] args) {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

My Startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.UseStaticFiles();
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseExceptionHandler("/Home/Error");
    }

    //app.UseCookiePolicy();

    app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

The NGINX sites-available file (where I think the issue is probably coming from) is:

server {
    listen 8081 default_server;
    listen [::]:8081 default_server;

    root /var/www/html;
    
    # Other NGINX configuration settings...
    
    location / {
        proxy_pass http://localhost:5000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /Home/ {
        proxy_pass http://localhost:5000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

I have found some related Stack Overflow questions, but none of them were able to fix my problem:

英文:

I am deploying a simple asp.net core app that uses only the home controller and a single post method. We have two internal networks one being only Windows machines and the other being only Linux machines. The asp core app has been deployed via NGINX on the linux side. To clarify I can view the website from the Window's side through the Linux Login node's IP Address 10.10.40.50:8081 as the URL. To view the website from the Linux side on the machine hosting the site, it is just localhost:5000.

The post method simply takes a single input and returns a corresponding pdf file to the input, and is as follows:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task&lt;IActionResult&gt; Create(string label) {
			if (ModelState.IsValid &amp;&amp; label.Length &gt; 0) {
				string newLabel = label.Trim().Split(&#39; &#39;)[0].ToUpper();
				if (fstickChecker.Contains(newLabel )) {
					var pdf = await CreatePDF(newLabel);
					return pdf;
				}
				else {
					return RedirectToAction(&quot;Index&quot;, new RouteValueDictionary(new { action = &quot;Index&quot;, err = &quot;Invalid label selected&quot; }));
				}
			}
			return View();
		}

The razor code:

 &lt;form method=&quot;post&quot; action=&quot;/Home/Create&quot;&gt;
                        @Html.AntiForgeryToken()
                        &lt;input size=&quot;60&quot; type=&quot;text&quot; name=&quot;label&quot; class=&quot;form-control&quot; id=&quot;labeler&quot; placeholder=&quot;Enter Label&quot; style=&quot;float:left;&quot;&gt;
                        &lt;div class=&quot;rotator-buttons&quot; style=&quot;padding-top:45px;&quot;&gt;
                            &lt;button type=&quot;submit&quot; class=&quot; btn btn-01 t-white&quot; style=&quot;float:left; height:40px;width:140px;background-color:#706552&quot;&gt;Create PDF&lt;/button&gt;
                        &lt;/div&gt;
                    &lt;/form&gt;

The post method operates correctly when run on a Windows machine via the VS 2017 debugger and from the linux machine hosting it (i.e. when using the localhost:5000 address).

However it fails when viewing the site from the Windows side (i.e. the 10.10.40:8081).

There is a GET method (named Search) which provides Search Engine type functionality in the textbox where the label is entered that operates correctly under all circumstances so it appears just the POST method is failing for whatever reason.

My program.cs portion:

public class Program {
		public static void Main(string[] args) {
			CreateWebHostBuilder(args).Build().Run();
		}

		public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
			WebHost.CreateDefaultBuilder(args)
				.UseStartup&lt;Startup&gt;();
	}

My startup.cs file

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
		app.UseStaticFiles();
			if (env.IsDevelopment()) {
				app.UseDeveloperExceptionPage();
			}
			else {
				app.UseExceptionHandler(&quot;/Home/Error&quot;);
			}

			
			//app.UseCookiePolicy();

			app.UseMvc(routes =&gt; {
				routes.MapRoute(
					name: &quot;default&quot;,
					template: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
			});
		}

The NGINX sites-available file (where I think the issue is probably coming from) is:

##
# You should look at the following URL&#39;s in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 8081 default_server;
        listen [::]:8081 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don&#39;t use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
                proxy_pass http://localhost:5000/;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                #proxy_set_header Connection &#39;upgrade&#39;;
                proxy_set_header Connection $http_connection;
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /Home/ {
                proxy_pass http://localhost:5000/;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $http_connection;
                #proxy_set_header Connection &#39;upgrade&#39;;
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }


        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
        #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        #}

        # deny access to .htaccess files, if Apache&#39;s document root
        # concurs with nginx&#39;s one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

I have found some related stackoverflow questions but none of them were able to fix my problem.
<https://stackoverflow.com/questions/47529210/400-status-error-when-posting-form-data-in-asp-net-core> and
<https://stackoverflow.com/questions/49126850/net-core-nginx-hosting-sockets-doesnt-allow-http-post?noredirect=1&lq=1>

答案1

得分: 0

我最终将“Create”的POST请求更改为GET,问题得以解决。虽然不是理想的解决方案,但在我的情况下,我可以应付。

英文:

I ended up changing the POST request for "Create" to a GET, and that solved the issue. Not ideal, but for my situation I could get away with it.

huangapple
  • 本文由 发表于 2020年1月4日 00:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定