【问题标题】:ASP .NET 4 Wev Api controller - modify response typeASP .NET 4 Wev Api 控制器 - 修改响应类型
【发布时间】:2012-09-12 17:54:16
【问题描述】:

假设我有一个简单的 Web API 控制器。结果,我想返回一个基本的 .NET 类型。例如:

public class LoginController : ApiController
{
    [HttpPost]
    public bool Authenticate(LoginUserViewModel loginUserViewModel)
    {
        return true;
    }
}

即使所有浏览器的请求完全相同,我也会在不同的浏览器中得到不同的结果。 在 Chrome 和 IE7 中,响应标头中的 Content-Type 为 application/json; charset=utf-8,响应值等于“true”。 Firefox 将响应 Content-Type 识别为 application/xml; charset=utf-8 并将响应值设置为:

"<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>"

有没有办法在服务器端设置响应类型,使其始终相同? 谢谢。

更新:这是我用来调用我的控制器的 JavaScript。

                    Ext.Ajax.request({
                    async: false,
                    url: 'Login/Authenticate',
                    defaultHeaders: { 'Accept': 'application/json' },
                    jsonData: user,
                    success: function (response, options) {
                        if (response.responseText !== 'true') {
                            Ext.Msg.alert('Error', 'Login failed, please try again');
                        } else {
                            document.location = 'Main.aspx';
                        }
                    },
                    failure: function (response, options) {
                        Ext.MessageBox.hide();
                        Ext.Msg.alert('Error', 'Server error. Cannot authenticate user.');
                    }
                });

【问题讨论】:

  • 你能说明你是如何调用这个控制器动作的吗?你提到了一些浏览器,所以我猜你写了一些 javascript 或其他东西来调用它。你能显示这个javascript吗?
  • 当然。现在将更新我的问题。

标签: http asp.net-mvc-4 asp.net-web-api httpresponse


【解决方案1】:

这是因为浏览器发送不同的 Accept 标头。 Web API 使用接受标头来确定响应的内容类型。默认情况下,Web API 会在其 configuration.Formatters 集合中加载一些不同的格式化程序。

强制响应为特定媒体类型的一种方法是删除所有现有的格式化程序并仅添加您想要的。

configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());

【讨论】:

  • 谢谢,这有帮助!但我仍然不清楚为什么 FF 没有从我的标题中选择“接受”属性:( 请参阅上面的 js 代码。
  • @BashirMagomedov 在这些情况下,我会启动 Fiddler 并准确观察 FF 发送的内容。我没有意识到您正在使用 JS 手动设置接受标头。
猜你喜欢
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
相关资源
最近更新 更多