You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Contact Action无法返回1/2位ID却可返回3位ID问题

问题

我写了一个Contact Action方法,返回类型是int,参数是int id。现在碰到个奇怪的问题:路由里传1位或2位数字的id(比如1、22)时,没法正常返回这个id;但传3位数字的id(比如111、222)却能正常显示结果。

相关代码

HomeController.cs

using _10_TagHelpersDemo.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace _10_TagHelpersDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public int Contact(int id)
        {
            return id;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Program.cs

namespace _10_TagHelpersDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}

原因分析

问题出在Action的返回值处理上:当你直接返回int类型时,ASP.NET Core会触发内容协商机制。1-2位数字大多属于合法的HTTP状态码范围(比如200、404都是标准状态码),框架会把这些数字当成状态码返回,显示对应的状态页面而不是你要的数字;而像111这类3位数字不属于标准HTTP状态码,框架才会把它当成普通文本返回给前端。

解决方案

有两种简单的解决方式:

方式一:修改返回类型为IActionResult,明确返回文本

把Contact方法改成这样,用Content方法指定返回纯文本:

public IActionResult Contact(int id)
{
    return Content(id.ToString());
}

方式二:添加特性指定返回格式

保持返回int不变,给方法加上[Produces("text/plain")]特性,强制框架返回纯文本,避免误判:

[Produces("text/plain")]
public int Contact(int id)
{
    return id;
}

内容的提问来源于stack exchange,提问作者Ashan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:05:12