是否可以仅将一个类的MediaTypeFormatter更改为JSON? [英] Is it possible to change the MediaTypeFormatter to JSON for only one class?
问题描述
我有一个Web API,其中全局配置配置为使用:XmlMediaTypeFormatter
I have a web api, where the global configuration is configured to use: XmlMediaTypeFormatter
我的问题是我不会使用新的控制器来扩展此Web api,而是使用JsonMediaTypeFormatter.
My problem is I wont to extend this web api with a new controller, that uses the JsonMediaTypeFormatter instead.
是否可以仅将一个API控制器类的MediaTypeFormatter更改为JSON?
Is it possible to change the MediaTypeFormatter to JSON for only one API Controller class?
我的问题不是返回JSON,我通过返回HttpResponseMessage对此进行了放大:
My problem is not returning JSON, I have accumplished this with returning HttpResponseMessage:
return new HttpResponseMessage
{
Content = new ObjectContent<string>("Hello world", new JsonMediaTypeFormatter()),
StatusCode = HttpStatusCode.OK
};
这是我提出的要求.如果我有一个具有两个属性的对象:
It's on the request I get the problem. If I have an object with two properties:
public class VMRegistrant
{
public int MerchantId { get; set; }
public string Email { get; set; }
}
我的控制器操作将VMRegistrant作为参数:
And my controller action takes the VMRegistrant as argument:
public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
{
// Save registrant in db...
}
但是问题是当我使用JSON调用动作时,它失败了.
But the problem is when I call the action with JSON it fails.
推荐答案
您可以让控制器返回 IHttpActionResult
并使用扩展方法
You can have your controller return an IHttpActionResult
and use the extension method HttpRequestMessageExtensions.CreateResponse<T>
and specify the formatter you want to use:
public IHttpActionResult Foo()
{
var bar = new Bar { Message = "Hello" };
return Request.CreateResponse(HttpStatusCode.OK, bar, new MediaTypeHeaderValue("application/json"));
}
另一种可能性是使用 ApiController.Content
方法:
Another possibility is to use the ApiController.Content
method:
public IHttpActionResult Foo()
{
var bar = new Bar { Message = "Hello" };
return Content(HttpStatusCode.OK, bar, new JsonMediaTypeFormatter(), new MediaTypeHeaderValue("application/json"));
}
一种可能性是,通过从流中读取并使用JSON解析器(例如Json.NET)从JSON中创建对象,来从 Request
对象自己读取和反序列化内容:
One possibility is to read and deserialize the content yourself from the Request
object via reading from the stream and using a JSON parser such as Json.NET to create the object from JSON:
public async Task<IHttpActionResult> FooAsync()
{
var json = await Request.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<VMRegistrant>(json);
}
这篇关于是否可以仅将一个类的MediaTypeFormatter更改为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!