c# - Web API 一次操作即可完成复杂和原始参数

标签 c# asp.net-web-api

我有一个 ASP.NET Web API 操作:

[HttpPost]
public void test(myCustomObj Entity)
{

}

JSON 数据是:

{
    "ID": "1",
    "Name": "ilhan",
    "surname": "aksu"
}

到目前为止,我的代码运行良好。但是,当我添加新的原始参数时:

[HttpPost]
public void test(myCustomObj Entity, [FromBody] string strdata)
{

}

当我发布以下 JSON 时:

{
    "Entity": {
        "ID": "1",
        "Name": "ilhan",
        "surname": "aksu"
    },
    "strdata": "testdata"
}

服务器返回500内部服务器错误

如何格式化 JSON 数据或更改操作方法来解决此问题?

最佳答案

如果您要发布 json,则可以接受 string 参数:

[HttpPost]
public void Test(string jsonString)
{

}

也许还有一个序列化器帮助程序以避免污染代码:

public static class JsonSerializer
{
        public static string Serialize<T>(T t) where T : class
        {
            return JsonConvert.SerializeObject(t);
        }

        public static T Deserialize<T>(string s) where T : class
        {
            return (T)JsonConvert.DeserializeObject(s, typeof(T));
        }
}

然后在您的方法中,您可以具体化 json 有效负载:

[HttpPost]
public void Test(string jsonString)
{
    var o = JsonSerializer.DeserializeObject(jsonString, typeof(MyObject));

    // ...
}    

如果您返回 json,则可能如下所示:

[HttpGet]
public JsonResult GetTest()
{
    var i = YourService.GetSomethingById(1);

    iSerialized = JsonSerializer.Serialize(i);

    return new JsonResult
        {
            ContentEncoding = System.Text.Encoding.UTF8,
            ContentType = "application/json",
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = iSerialized
        };
}

关于c# - Web API 一次操作即可完成复杂和原始参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233832/

相关文章:

javascript - 带有 AngularJS CORS 的 IE9、IE8 返回 “Access is denied” - ASP.NET WebApi

c# - 我们什么时候需要在 dot net c# 中调用 Dispose()?

c# - WPF 如何在文本框中使用验证规则而不创建额外的属性以绑定(bind)到对话框中?

c# - 在 appdomain 中加载静态类

c# - 将基类发送到接收派生类的方法 - C#

asp.net-web-api - 在 ASP.NET 5 MVC 6 应用程序中使用 Web API

asp.net-web-api - 带有 OWIN OAuth Bearer token 的 Web Api 2

c# - AWS Lambda c# 异步 API 调用

wcf-web-api - CaSTLe.ActiveRecord.dll 与 ASP.NET MVC 4 Web API 不兼容

c# - OWIN 托管的 web api : using windows authentication and allow anonymous access