首页 > 解决方案 > MVC Controller 和 MVC ControllerBase 中的 httppost 函数相同,但在 ControllerBase 中发现错误

问题描述

我创建了 Web MVC Core 项目并有两个控制器,其中主控制器是控制器,会话数据控制器是控制器基础我放置与以下相同的功能

[HttpPost]
        public async Task<SessionInfo> GetSessionInfo(string SessionID)
        {
            Console.WriteLine($"Main.GetSessionInfo({SessionID})");
            var getSession = await SessionService.GetSessionInfoAsync(int.Parse(SessionID));
            if (getSession == null) return null;
            return new()
            {
                returnstartdate = getSession.dtStartTime.HasValue ? getSession.dtStartTime.Value.ToString("dd/MM/yy HH:mm:ss") : string.Empty,
                returnenddate = getSession.dtEndTime.HasValue ? getSession.dtEndTime.Value.ToString("dd/MM/yy HH:mm:ss") : string.Empty
            };

        }

为了查看,在Javascript中我调用如下函数

function cbSessionChange() {
       
        var url = '@Url.Action("GetSessionInfo", "SessionData")'; 

        var selectvalue = $("#cbSessionList").val(); // Confirm have value
        console.log(`cbSessionList.val : ` + selectvalue.toString())

        $.post(url, { SessionID :selectvalue.toString()},
            function (data) {

                $('#txtDateFr').val(data.returnstartdate);
                $('#txtDateTo').val(data.returnenddate);

            }
        ,'json')
    };

但是,如果我在 Controller 中调用 GetSessionInfo(SessionID) 是有效的,那么在 ControllerBase 中调用 GetSessionInfo(SessionID) 时会得到空参数值。但是,我尝试使用邮递员来测试这两个功能是否都有效。

我能知道里面有什么不对吗?

谢谢

标签: jqueryajaxasp.net-core-mvcasp.net-core-webapi

解决方案


$.post方法默认内容类型是application/x-www-url-formencoded.

如果你的 ControllerBase 声明了[ApiController]属性,它会导致模型绑定系统默认绑定来自 body的数据 (内容类型是application/json)。

[FromForm]为了满足您的要求, ControllerBase 中的特定属性:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpPost]
    public async Task<SessionInfo> GetSessionInfo([FromForm]string SessionID)
    {
         //...
    }
}

或者只是删除[ApiController]

[Route("api/[controller]")]
//[ApiController]
public class ValuesController : ControllerBase
{
    [HttpPost]
    public async Task<SessionInfo> GetSessionInfo(string SessionID)
    {
         //...
    }
}

更新:

如果你想application/json通过 ajax 发布数据,改变如下:

<script>
function cbSessionChange() {

    var url = '@Url.Action("GetSessionInfo", "SessionData")';
    var selectvalue = 1; // Confirm have value
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: url,
        data: JSON.stringify(selectvalue.toString()),   //add this..
        dataType: "json",
        success: function (result, status, xhr) {
            $('#txtDateFr').val(result.returnstartdate);
            $('#txtDateTo').val(result.returnenddate);
        },
        error: function (xhr, status, error) {
            alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        }
    });
}

控制器:

public class SessionDataController : Controller
{
    [HttpPost]
    public async Task<SessionInfo>  GetSessionInfo([FromBody] string SessionID)
    {
         //...
    }
}

推荐阅读