【问题标题】:JsonResult does not contain a constructor that takes 1 argumentJsonResult 不包含带有 1 个参数的构造函数
【发布时间】:2022-01-22 16:55:15
【问题描述】:

我目前正在使用 JsonResult。有一个问题:如果我在我的 UserService 中调用 JsonResult,我将无法使用参数调用它,但是如果我在 UserController 中调用它,它可以使用我的参数。所以我现在的问题是,架构与控制器中的架构相同,所以出了什么问题?

UserService.cs:

public class UserService : IUserService
{
    private readonly IMapper mapper;
    private readonly ILogger<UserService> logger;

    public UserService(
        IMapper mapper,
        ILogger<UserService> logger)
    {
        this.mapper = mapper;
        this.logger = logger;
    }

    private static IList<Contact> GetStaticContacts(string fileName)
    {
        var jsonText = System.IO.File.ReadAllText(fileName);
        var contacts = JsonSerializer.Deserialize<IList<Contact>>(jsonText);
        return JsonResult(contacts);
    }

    Task<IList<Contact>> IUserService.GetNationalCoordinators()
    {
        return new JsonResult(GetStaticContacts("Test1.json"));
    }

    Task<IList<Contact>> IUserService.GetLocalCoordinators()
    {
        return new JsonResult(GetStaticContacts("Test2.json"));
    }

    Task<IList<Contact>> IUserService.GetMedicalAdvisors()
    {
        return new JsonResult(GetStaticContacts("Test3.json"));
    }
}

用户控制器:

public async Task<IActionResult> GetLocalCoordinators(CancellationToken cancellationToken = default)
    {
            var contacts = await userService.GetLocalCoordinators();
            var result = mapper.Map<IList<ContactDto>>(contacts);
            return new JsonResult(result);
    }

【问题讨论】:

    标签: c# json service interface controller


    【解决方案1】:

    看看这个 -> JsonResult in services layer

    还有关于 JsonResult 的文档 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.jsonresult?view=aspnetcore-6.0 指定 JsonResult 对象来自控制器中使用的 ActionResult。

    【讨论】:

    • 这对我帮助不大,因为我也不应该调用控制器的类...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2012-08-21
    相关资源
    最近更新 更多