将结果“15”更改为“{”结果“:15}`

时间:2017-11-13 05:49:09

标签: c# asp.net json

我正在创建一个ASP.NET Web API,它从dll文件中调用一个附加函数,并查找用户在URL中输入的数字的总和。例如:http://localhost:52241/api/dlladdition/9/6(用户输入数字9和6)。结果将是15。我希望结果类似于{ "result" : 15 }。我如何实现这一目标?

以下是我的代码:

dll文件

Mathclass.cs

public static class MathClass
{
    //method for Addition
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}

ASP.NET Web API

Addition.cs

using ClassLibraryDll;
public class Addition
{
    public static int num1 { get; set; }
    public static int num2 { get; set; }

    public static int sum = MathClass.Add(num1, num2);
}

AdditionController.cs

private Addition addition = new Addition();

public int GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return result;          
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DllAdditionApi",
            routeTemplate: "api/dlladdition/{num1}/{num2}",
            defaults: new { action = "Get", controller = "DllAddition" }
        );
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",
            StringComparison.InvariantCultureIgnoreCase,true,"application/json")
       );

    }

3 个答案:

答案 0 :(得分:2)

这是你能做的。为您的返回数据创建一个新模型

public class AdditionResult
{
    public int Result {get; set;}
}

public AdditionResult GET(int num1, int num2)
{
    int sum = ClassLibraryDll.MathClass.Add(num1, num2);
    var addResult = new AdditionResult();
    addResult.Result = sum;
    return addResult;          
}

答案 1 :(得分:1)

更改控制器的结果类型,然后您可以返回一个投射所需形状的匿名类:

[Route("api/dlladdition/{num1}/{num2}")]
public IHttpActionResult GET(int num1, int num2)
{
    var res = ClassLibraryDll.MathClass.Add(num1, num2);
    return Ok(new {result = res});
}

另一个建议是使用WebApi RouteAttribute执行定制的路由映射,而不是为了相同的目的而使用全局config.Routes.MapHttpRoute。 (您已通过调用RouteAttributes

注册config.MapHttpAttributeRoutes();

答案 2 :(得分:0)

只需返回具有Result属性的匿名类型的对象。 Asp.net将为您格式化为JSON:

public Object GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return new 
    {
        Result = result
    };
}