c# – 是否可以将MediaTypeFormatter更改为只有一个类的JSON?
我有一个web api,其中全局配置配置为使用:
XmlMediaTypeFormatter 我的问题是我不会使用新的控制器扩展这个web api,而是使用JsonMediaTypeFormatter. 是否可以仅为一个API控制器类将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; } } 我的控制器操作将VMRegistrant作为参数: public HttpResponseMessage CreateRegistrant(VMRegistrant registrant) { // Save registrant in db... } 但问题是,当我用JSON调用该操作时,它失败了. 解决方法
您可以让控制器返回IHttpActionResult并使用扩展方法
HttpRequestMessageExtensions.CreateResponse<T> 并指定要使用的格式化程序:
public IHttpActionResult Foo() { var bar = new Bar { Message = "Hello" }; return Request.CreateResponse(HttpStatusCode.OK,bar,new MediaTypeHeaderValue("application/json")); } 另一种可能性是使用1(System.Net.HttpStatusCode,0,System.Net.Http.Formatting.MediaTypeFormatter,System.Net.Http.Headers.MediaTypeHeaderValue)" rel="nofollow" target="_blank"> public IHttpActionResult Foo() { var bar = new Bar { Message = "Hello" }; return Content(HttpStatusCode.OK,new JsonMediaTypeFormatter(),new MediaTypeHeaderValue("application/json")); } 编辑: 一种可能性是通过读取tge流并使用JSON解析器(如Json.NET)从JSON创建对象,从Request对象中自行读取和反序列化内容: public async Task<IHttpActionResult> FooAsync() { var json = await Request.Content.ReadAsStringAsync(); var content = JsonConvert.DeserializeObject<VMRegistrant>(json); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |