gpt4 book ai didi

c# - 是否可以仅将一个类的 MediaTypeFormatter 更改为 JSON?

转载 作者:太空狗 更新时间:2023-10-29 20:27:10 25 4
gpt4 key购买 nike

我有一个 web api,其中全局配置被配置为使用:XmlMediaTypeFormatter

我的问题是我不会用一个新的 Controller 扩展这个 web api,而是使用 JsonMediaTypeFormatter。

是否可以仅将一个 API Controller 类的 MediaTypeFormatter 更改为 JSON?

我的问题不是返回 JSON,我已经通过返回 HttpResponseMessage 完成了这个:

return new HttpResponseMessage
{
Content = new ObjectContent<string>("Hello world", new JsonMediaTypeFormatter()),
StatusCode = HttpStatusCode.OK
};

这是我遇到问题的请求。如果我有一个具有两个属性的对象:

public class VMRegistrant 
{
public int MerchantId { get; set; }
public string Email { get; set; }
}

我的 Controller 操作将 VMRegistrant 作为参数:

public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
{
// Save registrant in db...
}

但问题是当我使用 JSON 调用操作时它失败了。

最佳答案

你可以让你的 Controller 返回一个 IHttpActionResult并使用扩展方法 HttpRequestMessageExtensions.CreateResponse<T> 并指定您要使用的格式化程序:

public IHttpActionResult Foo()
{
var bar = new Bar { Message = "Hello" };
return Request.CreateResponse(HttpStatusCode.OK, bar, new MediaTypeHeaderValue("application/json"));
}

另一种可能性是使用 ApiController.Content 方法:

public IHttpActionResult Foo()
{
var bar = new Bar { Message = "Hello" };
return Content(HttpStatusCode.OK, bar, new JsonMediaTypeFormatter(), new MediaTypeHeaderValue("application/json"));
}

编辑:

一种可能是自己从 Request 中读取和反序列化内容通过从流中读取对象并使用 JSON 解析器(例如 Json.NET)从 JSON 创建对象:

public async Task<IHttpActionResult> FooAsync()
{
var json = await Request.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<VMRegistrant>(json);
}

关于c# - 是否可以仅将一个类的 MediaTypeFormatter 更改为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com